2

The Common Lisp Object System (CLOS) supports multiple dispatch (multimethods). When is this a useful feature in practice? I'm not just looking for an example of hypothetical functionality that would be easier to implement with multiple dispatch[1]. I'm looking for examples of where it's useful in real software, for any value of real that means it would get written for something other than just an example.

[1] In programming tutorials, are examples contrived more often than not?

3 Answers 3

8
  • Anytime you use the visitor pattern.
  • Anytime you have a binary operator that needs to dispatch on both params (eg. bullet hits rock vs bullet hits spaceship vs spaceship hits rock)
  • Anytime you want specialization based on the parameter (eg. C++'s vector<bool> specialization, component systems where the component may or may not exist)
2

An easy to understand example would be arithmetic, where you might have definitions for

(plus integer integer) (plus float integer) (plus integer float)

and so on.

Used carefully, this can be a wonderful mechanism. Used carelessly..well, you get what you deserve.

1
  • Having to define (plus float integer) and `(plus integer float) seems a little unfortunate. For every pair of nonidentical numerical types you wanted to use, you would have to define two methods. One could just call the other, but you'd still have to write it. I suppose a macro could help with that.
    – user55019
    Jul 26, 2012 at 15:35
0

You can use them for generalized setters.

Instead of writing

(defmethod set-[specific-property] ((obj obj-type)) ())

for each [specific-property] setter that you want, you can use a single generic function to dispatch:

(defmethod set- ((prop (eql :foreground)) (obj window)) ())

(defmethod set- ((prop (eql :background)) (obj t)) ())

etc...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.