The following piece of Clojure code results in java.lang.StackOverflowError when I call it with (avg-bids 4000 10 5). I try to figure out why, since sum-bids is written as a tail-recursive function, so that should work. Using Clojure 1.2.
Anyone knows why this happens?
(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)))
mapis lazy, and you’re building a very deeply nested mapping of mappings viarecur. The backtrace is a bit cryptic, but look closely and you can see map, map, map…One way to fix it is to put
doallaround it to defeat laziness.