This is not an answer to your question, but in the interest of writing "nice" clojure code, I wanted to point out a few things with your example.
One of the benefits of the functional style is the ability to compose functions together. But if you take a look at the functions you've written, they individually don't do much without depending on functionality provided elsewhere.
For example, stream-builder
just returns a two-element list of n
and an anonymous function to handle pseudo-recursion.
My guess is that you were trying to go for a lazy sequence, but doing it that way requires support functions that are aware of the implementation details to realize the next element, namely, stream
and second$
. Thankfully you can instead accomplish it as follows:
(defn stream-builder [f x] ; f is idiomatic for a function arg
(lazy-seq ; n is idiomatic for a count, so use x instead
(cons x
(stream-builder f (f x)))))
The above will actually return an infinite sequence of values, so we need to pull out the limiting behavior that's bundled inside stream
:
(defn limit [n coll] ; coll is idiomatic for a collection arg
(lazy-seq ; flipped order, fns that work on seqs usually take the seq last
(when (pos? n)
(when-let [s (seq coll)]
(cons (first s)
(limit (dec n) (next s)))))))
The above will lazily return up to n
elements of coll
:
user=> (limit 5 (stream-builder inc 1))
(1 2 3 4 5)
In the end, each function does one thing well, and is composable with other functions:
Finally, you defined odd
to be the lazy sequence of odd integers. The danger is that sequence is going to stick around as it gets realized (this is known as "holding onto the head" of a sequence). This can unnecessarily take up excess memory to hold onto every element ever realized, and prevents garbage collection.
To solve this, either do not def the lazy sequence, or def it with the limit, e.g.:
(def odds (limit 23 (stream-builder #(+ 2 %) 1)))
For future reference, what we have just written is available in the core lib as iterate
and take
, respectively:
user=> (take 5 (iterate inc 1))
(1 2 3 4 5)