Skip to content

Instantly share code, notes, and snippets.

@Eleonore9
Last active January 29, 2016 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eleonore9/d7bbd5797449fb4d2082 to your computer and use it in GitHub Desktop.
Save Eleonore9/d7bbd5797449fb4d2082 to your computer and use it in GitHub Desktop.
Clojure thoughts and tips

Multimethods

-> an implementation of polymorphism in Clojure

What Clojure doc says:

A Clojure multimethod is a combination of a dispatching function, and one or more methods. When a multimethod is defined, using defmulti, a dispatching function must be supplied. This function will be applied to the arguments to the multimethod in order to produce a dispatching value.

It's easier to understand when looking at an example. Here's an example from Clojure for the brave and true:

That's how a multimethod is defined:

(ns were-creatures)

(defmulti full-moon-behavior 
  (fn [were-creature] 
    (:were-type were-creature)))

(defmethod full-moon-behavior :wolf
  [were-creature]
  (str (:name were-creature) " will howl and murder"))
  
(defmethod full-moon-behavior :simmons
  [were-creature]
  (str (:name were-creature) " will encourage people and sweat to the oldies"))

And now that's how the multimethod is used:

(full-moon-behavior {:were-type :wolf
                     :name "Rachel from next door"})
; => "Rachel from next door will howl and murder"

(full-moon-behavior {:name "Andy the baker"
                     :were-type :simmons})
; => "Andy the baker will encourage people and sweat to the oldies"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment