Clojure style multimethods in python(codeblog.dhananjaynene.com) |
Clojure style multimethods in python(codeblog.dhananjaynene.com) |
(defmulti say :whatiz)
(defmethod say ::feline [_] (println "MEOW"))
(say {:whatiz ::feline})
; MEOW
We would expect that nothing would happen if we then call it with the following: (say {:whatiz ::lion})
; No method in multimethod 'say' for dispatch value: :user/lion
But we can define a hierarchy on the fly with the following: (derive ::lion ::feline)
And now we have a whimpy lion: (say {:whatiz ::lion})
; MEOW
This is good for simulating derived behaviors without the baggage of explicitly grouping those behaviors with the type. The multimethod dispatch and the hierarchical dispatch are completely open for extension. This is really cool.