Created
April 23, 2011 03:10
-
-
Save kbaribeau/938215 to your computer and use it in GitHub Desktop.
Tail recursive and non-tail recursive implementations of reverse and factorial in clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn recursive-reverse [coll] | |
(if (= 0 (count coll)) | |
[] | |
(concat (recursive-reverse (drop 1 coll)) (take 1 coll)))) | |
(defn recursive-reverse [coll] | |
(loop [coll coll | |
acc []] | |
(if (empty? coll) | |
acc | |
(recur (rest coll) (cons (first coll) acc))))) | |
(defn factorial [n] | |
(if (zero? n) | |
0 | |
(if (= n 1) | |
1 | |
(* n (factorial (dec n)))))) | |
(defn factorial [n] | |
(if (zero? n) | |
0 | |
(loop [n n | |
acc 1] | |
(if (= n 1) | |
acc | |
(recur (dec n) (* n acc)))))) |
edit: added factorial
edit: made use of 'rest' and 'first' instead of 'drop 1' and 'take 1', thanks to @dnwiebe
there is a mistake, (factorial 0) is 1, not 0 !
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I did this while working through the cloure koans. Teach me shortcuts and style points if you got 'em!