In Python, you could limit generic dispatch to argument type only without losing generality since you could override the `isinstance` operator. For instance, you could define a `const()` type so that `isinstance(x, const(100))` is true if and only if `x == 100`. Then your example could be written in Python as:
foo = generic()
foo.when(const(0))
def foo_0(x): print "passed in zero"
foo.when(const(100))
def foo_100(x): print "passed in 100"
foo.when(const(200))
def foo_200(x): print "passed in 200"
foo.when(int)
def foo_default(x): print "passed in", x
This is not as elegant as in a language with native support for generic functions, but it works. I wish mainstream languages started to adopt multi-methods; it's conceptually very simple and much more extension-friendly than traditional OOP. Sadly it doesn't seem to happen.As far as I know, no. I could be wrong, but I think how it works is this: each method is added to a map for that multimethod. When dispatching, the dispatch function is applied to the arguments and the result is used as the key into the map of methods. I'm pretty sure that the compiler could optimise the lookup too, though I don't know if Clojure does or not.
Thats just what I would do if I wrote Clojure - I don't actually know how Clojure manages it in real life (and am too lazy to check).
Yeah. I've always wished that languages like C++ had two things: multimethods and ML-style pattern matching (well, three things - I guess you'd want ML-style parametric types to go with the pattern matching).
Quick example:
(written off the top of my head, so excuse any mistakes..)I'm only using a single argument here and I'm dispatching on a function of its value. I could just as easily dispatch on multiple arguments (or an arbitrary amount).