【发布时间】:2016-08-10 18:16:32
【问题描述】:
如何在 Clojure 中将非尾递归与同步记忆和有限堆栈消耗(因此没有堆栈溢出风险)结合起来?同步记忆是指记忆/缓存必须在线程之间同时有效地共享。
我的具体情况如下:
; g() is non recursive
; i is an integer
; h is a hash with int keywords and vector of ints values
; w is a hash with int keywords and int values
(defn g [i h w]
(filter
#(-> (w %)
(= i))
(h i)))
; f is recursive, recurses non-trivially (non-tail, multiple times)
; TODO: be memoizable (ideally in a synchronized way, for parallelism)
; TODO: pose no risk stack overflow
(defn f [i h w]
(if (nil? (h i))
0
(let [part_sum
(map ; will change this map to pmap or pvmap
#(f % h w)
(g i h))]
(-> (reduce + part_sum)
(/ 2)
(+ 1)))))
; trivial, shown for completeness
(defn ff [i h w]
(-> (f i h w)
(- 1)
(* 2)
(max 0)))
【问题讨论】:
-
关于避免堆栈溢出:我会说,这是不是 clojure 特定的一般问题。 Here你可以找到一些通用的方法来解决这个问题。
标签: concurrency clojure synchronization stack-overflow memoization