41 points · by coglethorpe · 17y ago · 8 comments
Care to elaborate? I know Common Lisp's multimethods dispatch on class and object identity
(defmethod foo ((obj class-name)) ..)
(defmethod foo ((obj (eql object)) ..)
The first one dispatches if obj is of class "class-name", and the second dispatches if obj and object are EQL (i.e. strictly equal by value or pointer.) and this second one allows you to do very clean switch/case style dispatching on actual values.How does clojure do it?
In the example below we dispatch my-add based on a function of the two arguments. This function returns a bool that determines the function to call, but it could return anything that you could then use to define the method upon (e.g. a symbol).
(defmulti my-add (fn [x y] (and (string? x) (string? y))))
(defmethod my-add true [x y]
(str x y))
(defmethod my-add false [x y]
(+ x y))
(my-add 3 4) ==> 7
(my-add "3" "4") ==> "34"