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?

  • 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)

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.

  • 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. – yakiv Jul 26 '12 at 15:35

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)) ())


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.