9. Runtime Polymorphism - Koans Walkthrough

This video covers runtime polymorphism. You can dispatch functions based on arity (number of parameters), or anything else through the power of multi-methods.

Here is the 09_runtime_polymorphism.clj source code:

(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] __)

  "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"})))

Clojure Koans Walkthrough in Light Table IDE

This screencast tutorial helps you learn the Clojure programming language. Experience the joy of Clojure in the Light Table IDE as we tour through the Clojure Koans, taking you all the way from Beginner to Intermediate to Advanced.

Clojure is a Lisp created by Rich Hickey that runs on the JVM, as an alternative to Java. ClojureScript can target the web browser environment, and node.js, by compiling down to JavaScript, using the Google Closure compiler. Clojure features immutability, functional programming, and being a Lisp, macros.