Skip to content

Instantly share code, notes, and snippets.

@sudowork
Created April 16, 2013 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudowork/5394099 to your computer and use it in GitHub Desktop.
Save sudowork/5394099 to your computer and use it in GitHub Desktop.
; NON-tail recursive version of size
; because the recursive call must be returned to the caller
(defn non-tail-size [v]
(if (empty? v)
0
(inc (non-tail-size (rest v)))))
user=> (non-tail-size [1 2 3])
3
user=> (non-tail-size (range 10000))
StackOverflowError clojure.core/range/fn--4269 (core.clj:2664)
; now for the tail recursive version (excuse the crappiness)
(defn tail-size [v]
(let [helper (fn itsame [xs acc]
(if (empty? xs)
acc
(itsame (rest xs) (inc acc))))]
(helper v 0)))
user=> (tail-size (range 10000)) ; STILL stack overflows because there's no automatic TCO
StackOverflowError clojure.core/range/fn--4269 (core.clj:2664)
; now let's actually optimize using recur and loop
(defn size [v]
(loop [xs v, acc 0]
(if (empty? xs)
acc
(recur (rest xs) (inc acc)))))
user=> (size (range 100000)) ; WOOT! success :)
100000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment