adding runtime polymorphism

This commit is contained in:
Colin Jones 2010-02-14 08:19:13 +08:00 committed by Relevance, Inc.
parent f58864deda
commit 357b458241
2 changed files with 36 additions and 0 deletions

View File

@ -0,0 +1,35 @@
(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] __)
(meditations
"Some functions can be used in different ways - with no arguments"
(= __ (hello))
"With one argument"
(= __ (hello "world"))
"Or with many arguments"
(= __
(hello "Peter" "Paul" "Mary"))
"Multimethods allow more complex dispatching"
(= "Bambi eats veggies."
(diet {:species "deer" :name "Bambi" :age 1 :eater :herbivore}))
"Different methods are used depending on the dispatch function result"
(= "Simba eats animals."
(diet {:species "lion" :name "Simba" :age 1 :eater :carnivore}))
"You may use a default method when no others match"
(= "I don't know what Rich Hickey eats."
(diet {:name "Rich Hickey"})))

View File

@ -19,4 +19,5 @@
(load "about_functions") (load "about_functions")
(load "about_conditionals") (load "about_conditionals")
(load "about_higher_order_functions") (load "about_higher_order_functions")
(load "about_runtime_polymorphism")
(println "You have acheived clojure enlightenment. Namaste.") (println "You have acheived clojure enlightenment. Namaste.")