Created
April 28, 2021 17:00
-
-
Save Crowbrammer/659d69a282bf9deb1f5ddeb1c89b9baf to your computer and use it in GitHub Desktop.
Multimethods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns amazing-defmulti) | |
(defmulti needs-food | |
(fn [person] (:is-hungry person))) | |
(defmethod needs-food true [person] "This person needs food.") | |
(defmethod needs-food false [person] "This person is well fed.") | |
(def steve {:is-hungry true}) | |
(def joe {:is-hungry false}) | |
(defn needs-food-if [person] | |
(if (:is-hungry person) | |
"This person needs food." | |
"This person is well fed.")) | |
#_(= (needs-food steve) "This person needs food.") | |
#_(= (needs-food joe) "This person is well fed.") | |
(= (needs-food-if steve) "This person needs food.") | |
(= (needs-food-if joe) "This person is well fed.") | |
(defmulti attack | |
(fn [my-character] | |
(:class my-character))) | |
(defmethod attack :barbarian [my-character] (str (:name my-character) " swings his axe for lethal blow.")) | |
(defmethod attack :mage [my-character] (str (:name my-character) " waves the wand and unleashes fall of heavy bricks from the nether.")) | |
#_(attack {:class :barbarian :name "Patrick"}) | |
(attack {:class :mage :name "Aaron"}) |
A great cheatsheet!
If the multimethod only takes one parameter and only uses a keyword to get a value from a map, we can just use the keyword directly as the dispatch function:
(defmulti needs-food :is-hungry) (defmulti attack :class)
Yes! So efficient! 😊
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A great cheatsheet!
If the multimethod only takes one parameter and only uses a keyword to get a value from a map, we can just use the keyword directly as the dispatch function: