I'm learning Clojure by doing problems from rich4clojure repo. Problem 147 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:
(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)))))))
I decided to test it and compare it with solutions others came up with. For example, one user wrote:
(defn pascal [coll]
(lazy-seq
(cons coll
(pascal (let [middle (map #(apply +' %) (partition 2 1 coll))]
(concat [(first coll)] middle [(last coll)]))))))
I time both solutions by evaluating:
time (nth (nth (pascal [1]) 400) 50))
and it turns out that mine is faster (which is sort of expected because the other user relies on last 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?