From eb73f39c9e1636b75a5ce9350f6a33133e380441 Mon Sep 17 00:00:00 2001 From: Alex Lynham Date: Mon, 28 Oct 2019 16:50:49 +0000 Subject: [PATCH] Add some simple examples for multimethods --- resources/koans.clj | 5 ++++ src/koans/27_multimethods.clj | 44 +++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/koans/27_multimethods.clj diff --git a/resources/koans.clj b/resources/koans.clj index 3bbfd9c..8f9bb10 100644 --- a/resources/koans.clj +++ b/resources/koans.clj @@ -280,4 +280,9 @@ [2 4] [2 4] 6]}] + + ["27_multimethods" {"__" ["Hello, World!" + "Hello there" + 1 + 6]}] ] diff --git a/src/koans/27_multimethods.clj b/src/koans/27_multimethods.clj new file mode 100644 index 0000000..2e4f12f --- /dev/null +++ b/src/koans/27_multimethods.clj @@ -0,0 +1,44 @@ +(ns koans.27-multimethods + (:require [koan-engine.core :refer :all])) + +(defmulti multimethod-without-args + (fn [keyword-arg] keyword-arg)) + +(defmethod multimethod-without-args :first [_] + (str "Hello, World!")) + +(defmethod multimethod-without-args :second [_] + (str "Hello there")) + +(defmulti multimethod-with-args + (fn [opt-one opt-two] opt-one)) + +(defmethod multimethod-with-args :path-one [_ opts] + (:first-opt opts)) + +(defmethod multimethod-with-args :path-two [_ opts] + (let [numbers (:second-opt opts)] + (->> numbers + (map inc) + (reduce +)))) + +(defmethod multimethod-with-args :path-three [_]) + +(meditations + "A multimethod takes an one or more arguments to dispatch on" + (= __ + (multimethod-without-args :first)) + + "Though it can be ignored and represented by _ in defmethods" + (= __ + (multimethod-without-args :second)) + + "Alternatively, we can use the arguments in defmethods" + (= __ + (multimethod-with-args :path-one {:first-opt 1 + :second-opt 2})) + + "This allows us to something different in each method implementation" + (= __ + (multimethod-with-args :path-two {:first-opt 1 + :second-opt [0 1 2]}))) \ No newline at end of file