Multimethods
Dan Sugalski does a great job of explaining multimethods. And there’s more:
Haskell, for example, allows you to dispatch based on the values that are passed, as well as their types. This is a tremendously powerful mechanism, though one that’s not often implemented. (I have a nagging suspicion that’s as much because it becomes close to impossible to mathematically prove a program's correctness with this scheme as the cost, and the folks doing language research tend to be of a theoretical bent. I may be wrong, though)
I worked on a language that had where
clauses, a slight generalization of his example. You could say stuff say foo(a, b : Int) where a ~= b/2
or foo(e : E, l : Seq[E]) where e = head(l)
. The language was designed with theorem proving in mind. However, this does complicate some things. And what do you do if the where
clauses of the different methods aren’t disjoint?
Two more points:
- Objective-C’s categories are half way to multimethods. Methods don’t have to be locked up in the class definition; you can add them later.
- Apple’s Dylan language supports singleton types.
singleton(5)
creates a type that’s a subtype of5
’s type and whose only member is5
. This makes it possible to dispatch by value. Dylan also lets you make new number types with limited ranges, but I don’t recall exactly how that works; presumably those are also taken into account during dispatch. Another fun way to use singleton types is to let the multimethod dispatch system do memoizing for you. You create a new method specialized on singleton types for the arguments you received, and put it in the dispatch table.