Created
December 7, 2012 14:12
-
-
Save ponkore/4233490 to your computer and use it in GitHub Desktop.
fizzbuzz in Clojure (multimethod版)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;; ディスパッチ関数 | |
| (defn fizzbuzz-dispatch-fn [n] [(zero? (mod n 3)) (zero? (mod n 5))]) | |
| ;; マルチメソッドの定義(マッチングめちゃ強力!) | |
| (defmulti fizzbuzz fizzbuzz-dispatch-fn) | |
| (defmethod fizzbuzz [true false] [n] "fizz") | |
| (defmethod fizzbuzz [false true] [n] "buzz") | |
| (defmethod fizzbuzz [true true] [n] "fizzbuzz") | |
| (defmethod fizzbuzz :default [n] n) | |
| (defn run-fizzbuzz [n] (->> (range 1 n) (map fizzbuzz))) | |
| ;; (run-fizzbuzz 16) | |
| ;; => (1 2 "fizz" 4 "buzz" "fizz" 7 8 "fizz" "buzz" 11 "fizz" 13 14 "fizzbuzz") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment