Saturday, May 24, 2014

Clojure Koans Answers and Explanations - 9 - Runtime polymorphism

Let's look at the solutions for the next of Clojure Koans - Runtime polymorphism.


(
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)))
(defmethod diet :herbivore [a] __)
(defmethod diet :carnivore [a] __)
(defmethod diet :default [a] __)
 ; these need to be
(defmulti diet (fn [x] (:eater x)))
(defmethod diet :herbivore [a] (str (:name a) " eats veggies."))
(defmethod diet :carnivore [a] (str (:name a) " eats animals."))
(defmethod diet :default [a] (str "I don't know what " (:name a) " eats."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;1
(= __ (hello))
; from the definition of hello it is obvious
; that when no arguments are passed to hello
; "Hello world
(= "Hello World!" (hello))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;2
(= __ (hello "world"))
; on passing one arg "Hello you silly etc."
(= "Hello, you silly world." (hello "world"))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;3
(= __
     (hello "Peter" "Paul" "Mary"))
; Passing more than 2 args lets to the final
; statement being executed
(= "Hello to this group: Peter, Paul, Mary!"
     (hello "Peter" "Paul" "Mary"))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;4
(= "Bambi eats veggies."
     (diet {:species "deer" :name "Bambi" :age 1 :eater :herbivore}))
(= "Bambi eats veggies."
     (diet {:species "deer" :name "Bambi" :age 1 :eater :herbivore}))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;5
(= "Simba eats animals."
     (diet {:species "lion" :name "Simba" :age 1 :eater :carnivore}))
(= "Simba eats animals."
     (diet {:species "lion" :name "Simba" :age 1 :eater :carnivore}))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;6
 (= "I don't know what Rich Hickey eats."
     (diet {:name "Rich Hickey"})))
(= "I don't know what Rich Hickey eats."
     (diet {:name "Rich Hickey"}))




No comments:

Post a Comment