Adam P. wrote:
On Fri, Jan 28, 2011 at 5:13 PM, Charles Oliver N.
[email protected]wrote:And it would be even cooler if Ruby supported some form of type-driven
pattern matching, so you could have different method bodies for
different input types rather than checking them over and over again.
But that’s a post for another day
Not very quackish.
But it’s used all over the core and standard libraries.
I tried implementing my own version of Enumerable#inject, which has no
less than four overloads and is almost impossible to implement in
Ruby because of that:
Enumerable[$A]#inject($B) {|$B, $A| $B } → $B
Enumerable[$A]#inject {|$A, $A| $A } → $A
Enumerable[$A]#inject($B, Symbol) → $B
Enumerable[$A]#inject(Symbol) → $A
(For obvious reasons, Ruby doesn’t have a standardized syntax for
talking about types, so I made one up. I hope you get what I mean.)
For example, the Rubinius implementation of Enumerable#inject contains
about 8 lines of actual code (ignoring comments, blank lines and lines
consisting only of ‘end’ or ‘}’). Two implement the actual behavior of
inject, the other six basically implement an ad hoc,
informally-specified, bug-ridden, slow implementation of half of
argument-based dispatch.
In fact, almost every method in kernel/common/enumerable.rb in
Rubinius contains at least one line that does not actually contribute
anything to the logic of the method but instead changes the behavior
of the method in some way, shape or form based on the number or class
of the arguments.
And I’ve seen that in other code as well, not just Rubinius’s or my
own, and not just in code that tries to replicate stdlib behavior.
Several projects I know chose YARD over RDoc as their documentation
tool, because it allows them to at least document their overloads
easily, even if writing them is cumbersome.
Personally, I would enjoy being able to dispatch on arguments in
addition to receivers. Martin Odersky hinted that he is interested in
adding argument-based dispatch to Scala, it will be interesting to see
what he comes up with, although he also said that it’s a very hard
problem (because of its interactions with overloading) and will take
many years if it happens at all.
Note that I avoided the use of the term “overloading” and used
“argument-based dispatch” instead. I’m pretty sure that’s what the OP
meant, since overloading happens statically and simply doesn’t make
sense in Ruby.
jwm