Clojure Q&A - Recent questions tagged stackoverflow
https://ask.clojure.org/index.php/tag/stackoverflow
Stack overflow with lazy-seq
https://ask.clojure.org/index.php/13937/stack-overflow-with-lazy-seq
<p>I'm learning Clojure by doing problems from <a rel="nofollow" href="https://github.com/PEZ/rich4clojure">rich4clojure</a> repo. <a rel="nofollow" href="https://gist.github.com/PEZ/9dcf23444c51883c4318d69efcd5e9f7">Problem 147</a> asks one to create a function which returns a lazy sequence of rows following rules of Pascal triangle given initial row. For example, for [3 1 2], the next row is [3 4 3 2]. Here's my solution:</p>
<pre><code>(defn pascal
([row] (lazy-seq (cons row (__ row :next))))
([row _]
(lazy-seq
(let [next-row (map #(apply +' %) (partition 2 1 (concat '(0) row '(0))))]
(cons next-row (pascal next-row :next)))))))
</code></pre>
<p>I decided to test it and compare it with solutions others came up with. For example, one user wrote:</p>
<pre><code>(defn pascal [coll]
(lazy-seq
(cons coll
(pascal (let [middle (map #(apply +' %) (partition 2 1 coll))]
(concat [(first coll)] middle [(last coll)]))))))
</code></pre>
<p>I time both solutions by evaluating:</p>
<pre><code>time (nth (nth (pascal [1]) 400) 50))
</code></pre>
<p>and it turns out that mine is faster (which is sort of expected because the other user relies on <em>last</em> which is O(n)). However, when I try to calculate 1000th row, I get stack overflow error only in case of my function. I'm struggling to see why this happens because I shouldn't be increasing the stack size. What am I missing?</p>
Clojurehttps://ask.clojure.org/index.php/13937/stack-overflow-with-lazy-seqSun, 02 Jun 2024 19:14:33 +0000