Java.lang.StackOverflowError in clojure tail recursion

I ran into a 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)))))

although using a loop will make it work:

(defn recursive-reverse [lst]
  (loop [coll lst acc nil]
    (if (= coll '()) acc
        (recur (rest coll) (cons (first coll) acc)))))

What is wrong with the previous code without a loop?

+5
source share
2 answers

Your mistake here:

([coll] (recursive-reverse [coll nil]))

You call recursive-reversewith one argument (vector). This calls up the same list of function arguments, so it is recursive and creates a stack frame every time.

Change it to:

([coll] (recursive-reverse coll nil))

and you must be right.

( , , nil, '() next, rest. , , , .)

+7

:

(defn recursive-reverse
  ([coll] (recursive-reverse coll nil))
  ([coll acc]
    (if (= coll '()) acc
        (recur (rest coll) (cons (first coll) acc)))))

recursive-reverse , .

+1

All Articles