4 ms·
I wonder how Clojure deals with ambiguities when dispatching by arbitrary predicates. Also in this case, the overhead of of generic call will grow linearly wit
by xi 16y ago
I wonder how Clojure deals with ambiguities when dispatching by arbitrary predicates. Also in this case, the overhead of of generic call will grow linearly with the number of methods, right?
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.
- dkersten 16y agothe overhead of of generic call will grow linearly with the number of methods 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).