2014-01-26 00:04:22 +00:00
|
|
|
(ns koan-engine.runner)
|
|
|
|
(ns koans.13-recursion (:use koan-engine.core))
|
|
|
|
|
2010-11-07 16:17:58 +00:00
|
|
|
(defn is-even? [n]
|
2011-02-08 21:57:15 +00:00
|
|
|
(if (= n 0)
|
2011-10-26 02:55:54 +00:00
|
|
|
__
|
|
|
|
(___ (is-even? (dec n)))))
|
2010-11-07 16:17:58 +00:00
|
|
|
|
|
|
|
(defn is-even-bigint? [n]
|
2011-03-31 22:36:49 +00:00
|
|
|
(loop [n n
|
|
|
|
acc true]
|
|
|
|
(if (= n 0)
|
2011-10-26 02:55:54 +00:00
|
|
|
__
|
|
|
|
(recur (dec n) (not acc)))))
|
2010-11-07 16:17:58 +00:00
|
|
|
|
2011-03-31 22:36:49 +00:00
|
|
|
(defn recursive-reverse [coll]
|
|
|
|
__)
|
|
|
|
|
2010-11-03 03:55:34 +00:00
|
|
|
(defn factorial [n]
|
|
|
|
__)
|
|
|
|
|
|
|
|
(meditations
|
2010-11-07 16:17:58 +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))
|
|
|
|
|
2011-03-31 22:36:49 +00:00
|
|
|
"Reversing directions is easy when you have not gone far"
|
|
|
|
(= '(1) (recursive-reverse [1]))
|
|
|
|
|
2013-07-25 00:39:17 +00:00
|
|
|
"Yet it becomes more difficult the more steps you take"
|
2011-03-31 22:36:49 +00:00
|
|
|
(= '(5 4 3 2 1) (recursive-reverse [1 2 3 4 5]))
|
|
|
|
|
2010-11-03 03:55:34 +00:00
|
|
|
"Simple things may appear simple."
|
|
|
|
(= 1 (factorial 1))
|
|
|
|
|
|
|
|
"They may require other simple steps."
|
|
|
|
(= 2 (factorial 2))
|
|
|
|
|
|
|
|
"Sometimes a slightly bigger step is necessary"
|
|
|
|
(= 6 (factorial 3))
|
|
|
|
|
|
|
|
"And eventually you must think harder"
|
|
|
|
(= 24 (factorial 4))
|
|
|
|
|
|
|
|
"You can even deal with very large numbers"
|
2011-02-08 21:57:15 +00:00
|
|
|
(< 1000000000000000000000000N (factorial 1000N))
|
2010-11-03 03:55:34 +00:00
|
|
|
|
|
|
|
"But what happens when the machine limits you?"
|
2012-01-13 23:17:40 +00:00
|
|
|
(< 1000000000000000000000000N (factorial 100003N)))
|