octopusgrabbus
octopusgrabbus

Reputation: 10685

Clojure Library Recursion Without loop ... recur

I have a question about iterate and Clojure library funcs implemented similarly to iterate.

(defn iterate
2     "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects"
3     {:added "1.0"
4      :static true}
5     [f x] (cons x (lazy-seq (iterate f (f x)))))

Without loop ... recur does iterate not consume its stack because it is operating on a lazy-sequence?

Upvotes: 4

Views: 482

Answers (1)

Slartibartfast
Slartibartfast

Reputation: 8805

Yes, each time you force next element in lazy sequence, iterate is called once, therefore there is no (immediate) recursion, and no stack consuming.

Upvotes: 4

Related Questions