Add a recursive list processing example.

This commit is contained in:
Colin Jones 2011-03-31 17:36:49 -05:00
parent 7d9fb046bb
commit 1dd2e9ca86
3 changed files with 22 additions and 6 deletions

View File

@ -3,13 +3,11 @@ Concepts / Language Features
Agents Agents
Vars Vars
state identity lifetime state identity lifetime
lazy sequences
Metadata Metadata
Tuples - syntax Tuples - syntax
Pattern Matching Pattern Matching
immutability/side effects immutability/side effects
memoization memoization
recursive list processing
trampolining trampolining
reflection reflection
Java interop Java interop

View File

@ -4,10 +4,15 @@
(___ (is-even? (dec n))))) (___ (is-even? (dec n)))))
(defn is-even-bigint? [n] (defn is-even-bigint? [n]
(loop [n n acc true] (loop [n n
(if (= n 0) __ acc true]
(if (= n 0)
__
(recur (dec n) (not acc))))) (recur (dec n) (not acc)))))
(defn recursive-reverse [coll]
__)
(defn factorial [n] (defn factorial [n]
__) __)
@ -21,6 +26,12 @@
"Having too many stack frames requires explicit tail calls with recur" "Having too many stack frames requires explicit tail calls with recur"
(= false (is-even-bigint? 100003N)) (= false (is-even-bigint? 100003N))
"Reversing directions is easy when you have not gone far"
(= '(1) (recursive-reverse [1]))
"Yet more difficult the more steps you take"
(= '(5 4 3 2 1) (recursive-reverse [1 2 3 4 5]))
"Simple things may appear simple." "Simple things may appear simple."
(= 1 (factorial 1)) (= 1 (factorial 1))

View File

@ -115,8 +115,15 @@
'multiply-by-5 'multiply-by-5
'(comp dec square)]} '(comp dec square)]}
"recursion" {"__" [true 'acc "recursion" {"__" [true
'(loop [n n acc 1] 'acc
'(loop [coll coll
acc ()]
(if (seq coll)
(recur (rest coll) (conj acc (first coll)))
acc))
'(loop [n n
acc 1]
(if (zero? n) (if (zero? n)
acc acc
(recur (dec n) (* acc n))))] (recur (dec n) (* acc n))))]