philipbohun.com

Glojure by Example: Multimethods

A multimethod chooses an implementation with a dispatch function you write. That is open polymorphism without a type hierarchy, which is the practical counterpart of reaching for generics when the distinction is in the data.

(defmulti area :shape)

(defmethod area :rect [{:keys [w h]}]
  (* w h))

(defmethod area :circle [{:keys [r]}]
  (* 3 r r))

(defmethod area :default [_]
  0)

:shape is the dispatch function: a keyword that looks itself up in the argument. The integer 3 stands in for pi so the result stays an integer.

(println (area {:shape :rect :w 3 :h 4}))
(println (area {:shape :circle :r 2}))
(println (area {:shape :triangle}))

New shapes can be added later with another defmethod.

$ glj multimethods.glj
12
12
0

Next example: Atoms.