Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
; (sum 10) ;-> (+ 10 (sum 9))
; (sum 9) ;-> (+ 9 (sum 8))
; ...
; (sum 1) ;-> (+ 1 0)
(defn sum [n] ; foldr
(case n
1 1 ;(+ 1 0) ; 0 is initial value
(+ n (sum (dec n)))))
; [i s] -> [10 0] -> [9 10] -> [8 19] -> ... -> [1 54] -> [0 55]
(defn sum-loop-recur [n]
(loop [i n
s 0]
(case i
0 s
(recur (dec i) (+ s i)))))
; (f 10 0) -> (recur 9 10) -> (recur 8 19) -> ...
; ... -> (recur 1 54) -> (recur 0 55)
(defn sum-recur [n]
(letfn [(f [i s]
(case i
0 s
(recur (dec i) (+ s i))))]
(f n 0)))
; ref. プログラミング Clojure 第 2 版 P. 90
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment