;======================================================================================= ; lecture trace 3 -- introducing recursion ;======================================================================================= ;================================= ; factorial ;================================= (defn fact [n] (if (zero? n) 1 (* n (fact (dec n))) )) user=> (fact 5) 120 user=> (fact 1) 1 user=> (fact 0) 1 ;================================= ; sum of numbers up to some n ;================================= (defn sum-upto [n] (if (zero? n) 0 (+ n (sum-upto (dec n))) )) user=> (sum-upto 5) 15 ;================================= ; find the length of a list ;================================= (defn length [lis] (if (empty? lis) 0 (inc (length (rest lis))) )) user=> (length nil) 0 user=> (length '(cat rat frog dog)) 4 user=> (len '[a b c d e]) 5 ; better clojure style... (defn length [lis] (if-not (seq lis) 0 (inc (length (rest lis))) )) ; you may see some people do this... (defn length [lis] (if-not (first lis) 0 (inc (length (rest lis))) )) user=> (length []) 0 user=> (length '(egg beans chips and spam)) 5 ;================================= ; sum a list of numbers ;================================= (defn sum-list [lis] (if (empty? lis) 0 (+ (first lis) (sum-list (rest lis))) )) user=> (sum-list '(4 2 1 3 5)) 15 ; better style... (defn sum-list [lis] (if-not (seq lis) 0 (+ (first lis) (sum-list (rest lis))) )) ;================================= ; replace elements of a list ; with the word 'spam ;================================= (defn spam-all [lis] (if (empty? lis) () (cons 'spam (spam-all (rest lis))) )) user=> (spam-all '(cat 3 dog 4 rat 5)) (spam spam spam spam spam spam) ; better? (defn spam-all [lis] (if-not (seq lis) () (cons 'spam (spam-all (rest lis))) )) ;========================= ; replace all numbers only ; in a list with 'spam ;========================= (defn spam2 [lis] (cond (empty? lis) nil (number? (first lis)) (cons 'spam (spam2 (rest lis))) :else (cons (first lis) (spam2 (rest lis))) )) > (spam2 '(cat 3 dog 4 rat 5)) (cat spam dog spam rat spam) ; a couple of things to think about ;-------------------------------------- (defn f2 [n] (reduce * (map inc (range n)))) (defn f3 [n] (loop [n n r 1 ] (if (zero? n) r (recur (dec n) (* r n))) ))