Sunday, 2 September 2012

Clojure multimethods

Defmulti

Defmulti defines a multimethod call, the methods don't need to be defined yet. It can be as simple as the following

(defmulti salutation :gender)

With this defined now, we can add conditions in the form of multimethods

Defmethod

To add a condition to this we can use the following

(defmethod salutation :f [_] "Madam")
(defmethod salutation :m [_] "Sir")

This allows us to make calls to the function and have it transparently dispatch to the correct function based on the gender keyword in the map.

(salutation {:name "Kirsty" :gender :f})
"Madam"
(salutation {:name "Josh" :gender :m})
"Sir"

No comments:

Post a Comment