Skip to content

Instantly share code, notes, and snippets.

@kpuputti
Last active December 15, 2015 21:29
Show Gist options
  • Save kpuputti/5325851 to your computer and use it in GitHub Desktop.
Save kpuputti/5325851 to your computer and use it in GitHub Desktop.
SICP exercise 1.11 in Clojure
;; 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