我一直在尝试实现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)
答案 0 :(得分:8)
它打印最后的结果,吹了堆栈 所以这是REPL而不是你的代码。
用
替换最后一行(count (stress-test 99999))
并完成
堆栈跟踪有多次重复此模式:
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
编辑: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>