loop-recur如何抛出StackOverflowError?

LDo*_*ala 4 tail-recursion clojure

我一直在尝试实现chainl1的尾递归版本,但即使使用loop-recur它也会抛出StackOverflowError.这怎么可能,我该怎么做才能改变它?

(defn atest [state]
  (when-not (and (= "" state) (not (= (first state) \a))) 
      (list (first state) (. state (substring 1)))))
(defn op [state]
  (when-not (and (= "" state) (not (= (first state) \a)))
    (list #(list :| %1 %2) (. state (substring 1)))))
(defn chainl1-helper [x p op]
  (fn [state]
    (loop [x x
           state state]
      (if-let [xs (op state)]
        (when-let [xs2 (p (second xs))]
          (recur ((first xs) x (first xs2)) (second xs2)))
        (list x state)))))

(defn chainl1 [p op]
  (fn [state]
    (when-let [[v s] (p state)]
      ((chainl1-helper v p op) s))))
(def test-parse (chainl1 atest op))
(defn stress-test [n] (test-parse (apply str (take n (interleave (repeat "a") (repeat "+"))))))
(stress-test 99999)
Run Code Online (Sandbox Code Playgroud)

Art*_*ldt 8

它打印的最终结果是打击堆栈所以它是REPL而不是你的代码.

用.替换最后一行

(count (stress-test 99999))
Run Code Online (Sandbox Code Playgroud)

它完成了

堆栈跟踪有多次重复此模式:

 13:    core_print.clj:58 clojure.core/print-sequential
 14:    core_print.clj:140 clojure.core/fn
 15:      MultiFn.java:167 clojure.lang.MultiFn.invoke
Run Code Online (Sandbox Code Playgroud)

编辑:LDomagala指出打印级别是对这种崩溃的安全

user>  (set! *print-level* 20)
20
user> (stress-test 9999)
((:f (:f (:f (:f (:f (:f (:f (:f (:f (:f (:f (:f (:f (:f (:f (:f (:f (:f (:f # \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) \a) "")
user> 
Run Code Online (Sandbox Code Playgroud)

  • 我被告知你也可以使用(设置!*打印级别*20),因此只打印部分结果并且堆栈不会被烧毁. (3认同)