clojure-koans/14_recursion.clj

51 lines
1.2 KiB
Clojure
Raw Normal View History

(defn is-even? [n]
(if (= n 0)
2011-10-26 02:55:54 +00:00
__
(___ (is-even? (dec n)))))
(defn is-even-bigint? [n]
(loop [n n
acc true]
(if (= n 0)
__
(recur (dec n) (not acc)))))
(defn recursive-reverse [coll]
__)
(defn factorial [n]
__)
2010-11-03 03:55:34 +00:00
; "Recursion ends with a base case"
(= true (is-even? 0))
; "And starts by moving toward that base case"
(= false (is-even? 1))
; "Having too many stack frames requires explicit tail calls with recur"
(= false (is-even-bigint? 100003N))
; "Reversing directions is easy when you have not gone far"
(= '(1) (recursive-reverse [1]))
; "Yet it becomes more difficult the more steps you take"
(= '(5 4 3 2 1) (recursive-reverse [1 2 3 4 5]))
; "Simple things may appear simple."
2010-11-03 03:55:34 +00:00
(= 1 (factorial 1))
; "They may require other simple steps."
2010-11-03 03:55:34 +00:00
(= 2 (factorial 2))
; "Sometimes a slightly bigger step is necessary"
2010-11-03 03:55:34 +00:00
(= 6 (factorial 3))
; "And eventually you must think harder"
2010-11-03 03:55:34 +00:00
(= 24 (factorial 4))
; "You can even deal with very large numbers"
(< 1000000000000000000000000N (factorial 1000N))
2010-11-03 03:55:34 +00:00
; "But what happens when the machine limits you?"
(< 1000000000000000000000000N (factorial 100003N))