Lazy-seq and cons with recursion pattern no tail recursive, so what are other options?


The patter I mention would be something like:

(defn f [x] (lazy-seq (cons x (f (tx x)))))

This would use the call stack because the recursive call can’t use the recur function as it is not in tail position.

But what actually is trying to do is to generate a lazy infinity sequence of repeated transformations on an initial value (or seed).

What would be an alternative to achieve the same goal (lazy-seq) without using the call stack?

1 Like

Have a look at iterate and repeatedly


So the equivalent with iterate would be

(iterate tx x)

So clean.

Thank you very much!


You were close to a solution, the original definition of iterate is (cons x (lazy-seq (iterate f (f x)))). Today it’s a java class, probably because of its constant IReduce implementation that doesn’t build up an immediate sequence.

EDIT: Here is the JIRA ticket describing the reason of creating the java class.