-
Notifications
You must be signed in to change notification settings - Fork 0
/
Runtime Polymorphism
47 lines (27 loc) · 1.23 KB
/
Runtime Polymorphism
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
ClojureScript Koans Runtime Polymorphism Answers
http://clojurescriptkoans.com/#runtime-polymorphism/1
(defn hello
([] "Hello World!")
([a] (str "Hello, you silly " a "."))
([a & more] (str "Hello to this group: "
(apply str
(interpose ", " (concat (list a) more)))
"!")))
(defmulti diet (fn [x] (:eater x)))
1)Some functions can be used in different ways - with no arguments
(= "Hello World!" (hello))
2)With one argument
(= "Hello, you silly world." (hello "world"))
3)Or with many arguments
(= "Hello to this group: Peter, Paul, Mary!" (hello "Peter" "Paul" "Mary"))
4)Multimethods allow more complex dispatching
(= "Bambi eats veggies." (diet {:species "deer", :name "Bambi", :age 1, :eater :herbivore}))
(defmethod diet :herbivore [a] "Bambi eats veggies." )
5)Different methods are used depending on the dispatch function result
(= "Simba eats animals." (diet {:species "lion", :name "Simba", :age 1, :eater :carnivore}))
(defmethod diet :carnivore [a] "Simba eats
animals.")
6)You may use a default method when no others match
(= "I don't know what Rich Hickey eats." (diet {:name "Rich Hickey"}))
(defmethod diet :default [a] "I don't know
what Rich Hickey eats.")