Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

  • 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)
share|improve this answer

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.

share|improve this answer
    
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)) ())

etc...

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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