gpt4 book ai didi

clojure - 尾递归函数上的 StackOverflowError

转载 作者:行者123 更新时间:2023-12-02 23:10:41 26 4
gpt4 key购买 nike

当我使用 (avg-bids 4000 10 5) 调用以下 Clojure 代码时,会导致 java.lang.StackOverflowError。我试图找出原因,因为 sum-bids 是作为尾递归函数编写的,所以应该可以工作。使用 Clojure 1.2。

谁知道为什么会发生这种情况?

(ns fixedprice.core
(:use (incanter core stats charts)))

(def *bid-mean* 100)

(defn bid [x std-dev]
(sample-normal x :mean *bid-mean* :sd std-dev))

(defn sum-bids [n offers std-dev]
(loop [n n sum (repeat offers 0)]
(if (zero? n)
sum
(recur (dec n) (map + sum (reductions min (bid offers std-dev)))))))

(defn avg-bids [n offers std-dev]
(map #(/ % n) (sum-bids n offers std-dev)))

最佳答案

map 是惰性的,您正在通过 recur 构建非常深层嵌套的映射映射。回溯有点神秘,但仔细观察你可以看到 map , map , map ......

Caused by: java.lang.StackOverflowError
at clojure.lang.LazySeq.seq(LazySeq.java:56)
at clojure.lang.RT.seq(RT.java:450)
at clojure.core$seq.invoke(core.clj:122)
at clojure.core$map$fn__3699.invoke(core.clj:2099)
at clojure.lang.LazySeq.sval(LazySeq.java:42)
at clojure.lang.LazySeq.seq(LazySeq.java:56)
at clojure.lang.RT.seq(RT.java:450)
at clojure.core$seq.invoke(core.clj:122)
at clojure.core$map$fn__3699.invoke(core.clj:2099)
at clojure.lang.LazySeq.sval(LazySeq.java:42)
at clojure.lang.LazySeq.seq(LazySeq.java:56)
at clojure.lang.RT.seq(RT.java:450)
at clojure.core$seq.invoke(core.clj:122)
at clojure.core$map$fn__3699.invoke(core.clj:2099)
at clojure.lang.LazySeq.sval(LazySeq.java:42)
at clojure.lang.LazySeq.seq(LazySeq.java:56)
at clojure.lang.RT.seq(RT.java:450)
at clojure.core$seq.invoke(core.clj:122)
at clojure.core$map$fn__3699.invoke(core.clj:2099)

解决这个问题的一种方法是使用 doall 来克服懒惰。

(defn sum-bids [n offers std-dev]
(loop [n n sum (repeat offers 0)]
(if (zero? n)
sum
(recur (dec n) (doall (map + sum (reductions min (bid offers std-dev))))))))

user> (avg-bids 4000 10 5)
(100.07129114746716 97.15856005697917 95.81372899072466 94.89235550905231 94.22478826109985 93.72441188690516 93.32420819224373 92.97449591314158 92.67155818823753 92.37275046342015)

关于clojure - 尾递归函数上的 StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4249926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com