Created
December 7, 2012 13:24
-
-
Save ponkore/4233256 to your computer and use it in GitHub Desktop.
階乗の計算 in Clojure
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 fact-1 [n] | |
(if (= n 0) 1 | |
(*' n (fact-1 (dec n))))) | |
;;; 末尾再帰版 | |
(defn fact-2 | |
([n] (fact-2 n 1)) | |
([n acc] | |
(if (= n 0) acc | |
(fact-2 (dec n) (*' n acc))))) | |
;;; loop - recur 版 | |
(defn fact-3 [n] | |
(loop [cnt n acc 1] | |
(if (= cnt 0) acc | |
(recur (dec cnt) (*' cnt acc))))) | |
;;; fact (multimethod 普通の再帰版) | |
(defmulti fact-4 identity) | |
(defmethod fact-4 0 [n] 1) | |
(defmethod fact-4 :default [n] (*' n (fact-4 (dec n)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment