-
Notifications
You must be signed in to change notification settings - Fork 0
/
14_recursion.clj
58 lines (43 loc) · 1.33 KB
/
14_recursion.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
(ns koans.14-recursion
(:require [koan-engine.core :refer :all]))
(defn is-even? [n]
(if (= n 0)
true
(= false (is-even? (dec n)))))
(defn is-even-bigint? [n]
(loop [n n
acc true]
(if (= n 0)
acc
(recur (dec n) (not acc)))))
(defn recursive-reverse [coll]
(reduce conj '() coll))
(defn factorial [n]
(loop [n n
acc 1]
(if (= n 1)
acc
(recur (dec n) (* acc n)))))
(meditations
"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"
(= '(6 5 4 3 2) (recursive-reverse [2 3 4 5 6]))
"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"
(< 1000000000000000000000000N (factorial 1000N))
"But what happens when the machine limits you?"
(< 1000000000000000000000000N (factorial 100003N)))