I encountered the StackOverflowError for the following code:
(defn recursive-reverse
([coll] (recursive-reverse [coll nil]))
([coll acc]
(if (= coll '()) acc
(recur (rest coll) (cons (first coll) acc)))))
though using loop would make it work:
(defn recursive-reverse [lst]
(loop [coll lst acc nil]
(if (= coll '()) acc
(recur (rest coll) (cons (first coll) acc)))))
What goes wrong with the prior code without loop?
Your bug is here:
You’re calling
recursive-reversewith one argument (a vector). This calls the same argument list of the function, so it does it recursively and creates a stack frame every time.Change it to:
and you should be right.
(Also, separate issue, but I would generally do checking for
nilrather than'()and usingnextrather thanrest. I don’t think it has any real advantage in terms of performance or anything, but it seems cleaner to me.)