Skip to content

Instantly share code, notes, and snippets.

@kbaribeau
Created April 23, 2011 03:10
Show Gist options
  • Save kbaribeau/938215 to your computer and use it in GitHub Desktop.
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
(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))))))
@kbaribeau
Copy link
Author

I did this while working through the cloure koans. Teach me shortcuts and style points if you got 'em!

@kbaribeau
Copy link
Author

edit: added factorial

@kbaribeau
Copy link
Author

edit: made use of 'rest' and 'first' instead of 'drop 1' and 'take 1', thanks to @dnwiebe

@ar7hur
Copy link

ar7hur commented Oct 17, 2012

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