Last active
December 15, 2015 21:29
-
-
Save kpuputti/5325851 to your computer and use it in GitHub Desktop.
SICP exercise 1.11 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
;; f(n) = n if n < 3 | |
;; f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n >= 3 | |
(def rounds 30) | |
(println "== recursive ==") | |
(defn f-recursive [n] | |
(if (< n 3) | |
n | |
(+ (f-recursive (dec n)) | |
(* 2 (f-recursive (- n 2))) | |
(* 3 (f-recursive (- n 3)))))) | |
(time | |
(doseq [i (range rounds)] | |
(println i "=>" (f-recursive i)))) | |
(println "== \"iterative\" without tail recursion optimisation ==") | |
(defn f-iterative-iter [a b c n] | |
(cond | |
(= n 0) c | |
(= n 1) b | |
(= n 2) a | |
:else (f-iterative-iter (+ a (* 2 b) (* 3 c)) a b (dec n)))) | |
(defn f-iterative [n] | |
(f-iterative-iter 2 1 0 n)) | |
(time | |
(doseq [i (range rounds)] | |
(println i "=>" (f-iterative i)))) | |
(println "== iterative with tail recursion optimisation ==") | |
(defn f-iterative-tco [nn] | |
(loop [a 2 | |
b 1 | |
c 0 | |
n nn] | |
(cond | |
(= n 0) c | |
(= n 1) b | |
(= n 2) a | |
:else (recur (+ a (* 2 b) (* 3 c)) a b (dec n))))) | |
(time | |
(doseq [i (range rounds)] | |
(println i "=>" (f-iterative-tco i)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment