Created
April 16, 2013 07:32
-
-
Save sudowork/5394099 to your computer and use it in GitHub Desktop.
This file contains 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
; 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