Skip to content

Instantly share code, notes, and snippets.

@Crowbrammer
Created April 28, 2021 17:00
Show Gist options
  • Save Crowbrammer/659d69a282bf9deb1f5ddeb1c89b9baf to your computer and use it in GitHub Desktop.
Save Crowbrammer/659d69a282bf9deb1f5ddeb1c89b9baf to your computer and use it in GitHub Desktop.
Multimethods
(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"})
@NPException
Copy link

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)

@Crowbrammer
Copy link
Author

Crowbrammer commented Apr 29, 2021

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