Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท CLOS Object System

CLOS: Generic Functions, Methods and Multiple Dispatch

Learn CLOS generic functions and defmethod in Common Lisp: dispatch on argument classes, eql specializers, multiple dispatch and how methods are chosen.

A generic function is a function whose implementation is chosen at call time from a set of methods, depending on the classes of its arguments. This replaces the object.method() style with (method object ...), and it generalizes naturally to dispatching on several arguments at once (multiple dispatch).

The CLOS code is read-only because there is no Common Lisp runtime on this site. The JavaScript examples are labelled stand-ins that implement a small dispatcher to model the idea.

defgeneric and defmethod

LISP
(defclass shape () ())
(defclass circle (shape) ((radius :initarg :radius :reader radius)))
(defclass rect   (shape) ((w :initarg :w :reader w) (h :initarg :h :reader h)))

(defgeneric area (shape)
  (:documentation "Area of a shape."))

(defmethod area ((s circle))
  (* pi (expt (radius s) 2)))

(defmethod area ((s rect))
  (* (w s) (h s)))

(area (make-instance 'rect :w 3 :h 4))   ; => 12

defgeneric declares the name and its lambda list. Each defmethod supplies a specialized parameter, written (parameter class). An unspecialized parameter accepts anything (it is specialized on class t). If you skip defgeneric, defmethod creates the generic function implicitly, but writing the declaration is clearer and lets you add documentation.

Calling (area x) looks at the class of x, finds the applicable methods, and runs the most specific one. If no method applies, you get a no-applicable-method error.

JS Stand-in: a generic function with single dispatch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Methods are open

Anyone can add a method to an existing generic function for their own class, without editing the original code. This is how libraries extend each other. You can even specialize on built-in classes:

LISP
(defgeneric describe-it (x))

(defmethod describe-it ((x integer)) (format nil "the integer ~d" x))
(defmethod describe-it ((x string))  (format nil "the string ~s" x))
(defmethod describe-it ((x list))    (format nil "a list of ~d items" (length x)))
(defmethod describe-it (x)           (format nil "something else: ~a" x))

(describe-it 42)         ; => "the integer 42"
(describe-it "hi")       ; => "the string \"hi\""
(describe-it '(1 2 3))   ; => "a list of 3 items"
(describe-it 2.5)        ; => "something else: 2.5"

The last method (no specializer) is the fallback because every object is of class t.

eql specializers

You can dispatch on a specific value, not just a class, with (eql value):

LISP
(defgeneric handle-key (key))
(defmethod handle-key ((key (eql :quit)))  (format t "bye~%"))
(defmethod handle-key ((key (eql :help)))  (format t "help text~%"))
(defmethod handle-key (key)                (format t "unknown key ~s~%" key))

This replaces long case forms with extensible tables: another file can add (defmethod handle-key ((key (eql :save))) ...).

Multiple dispatch

All required parameters can be specialized, and the chosen method depends on all of them. This is where CLOS goes beyond most languages:

LISP
(defclass asteroid () ())
(defclass ship () ())
(defclass bullet () ())

(defgeneric collide (a b))
(defmethod collide ((a asteroid) (b ship))   (format t "ship destroyed~%"))
(defmethod collide ((a ship) (b asteroid))   (collide b a))
(defmethod collide ((a bullet) (b asteroid)) (format t "asteroid split~%"))
(defmethod collide ((a asteroid) (b asteroid)) (format t "asteroids bounce~%"))

With single-dispatch OOP you would need the visitor pattern. Here (collide x y) chooses by both classes. Methods are compared left to right: a method specialized more narrowly on the first argument wins; ties go to the second argument and so on.

JS Stand-in: dispatching on two arguments

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Lambda lists and congruence

All methods of a generic function must have congruent lambda lists: the same required and optional parameters, and compatible &key/&rest. Only the required parameters can be specialized. A generic function can also add keyword parameters by letting individual methods accept more keys than the generic requires, as long as the generic allows them (&key or &allow-other-keys).

Everything is a generic function

Many standard operations are generic: print-object, initialize-instance, make-instance, describe-object, slot-missing, documentation. Specializing them is how you customize printing, creation and more. For example:

LISP
(defmethod print-object ((p person) stream)
  (print-unreadable-object (p stream :type t)
    (format stream "~a" (person-name p))))

(make-instance 'person :name "Ada")   ; prints as #<PERSON Ada>

Next you will see how several applicable methods combine, with call-next-method and :before/:after/:around methods, in inheritance and method combination.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a generic function do when called?

    Dispatch picks the applicable methods and runs the most specific one (with method combination for others).
  2. 2. How do you dispatch on the exact keyword :quit?

    An eql specializer matches one particular object.
  3. 3. What makes CLOS dispatch 'multiple'?

    All required parameters can take part in choosing the method.
  4. 4. A call has no applicable method. What happens?

    The default no-applicable-method method signals an error, which you can handle with the condition system.

Summary

  • Methods belong to generic functions, not classes; defmethod specializes required parameters.
  • Dispatch chooses the most specific applicable method; t is the fallback.
  • eql specializers dispatch on values; any number of arguments can be specialized.
  • Methods can be added from anywhere, including for built-in classes.
  • Standard operations like print-object are generic and can be customized.

Next: Inheritance and Method Combination