为什么代理被阻止我的代码?

时间:2013-08-19 06:23:02

标签: clojure

说明
我有一个列表(名为large-number-list),其中包含许多数字,我想得到这些数字的总和。
现在我将列表分成三个元素作为一个要计算的组(该组将在代理的动作中计算),并将这三个元素的总和放入一个向量(命名结果)。
最后,我将元素一起累积在向量中。

代码如下:

;use agent to calculate many number  
(def result (agent []))  
(def large-number-list [1 2 3 4 5 6 7 8 9 10 11 12]);assume that large-number-list contains many number in it   
(defn doin3 [col do-fn]  
    (let [[x1 x2 x3 & rest-elem]  col  
         rest-len (count rest-elem)]  
         (println "x1 x2 x3" x1 x2 x3)  
         (println "rest-len is " rest-len)  
         (do-fn x1 x2 x3)  
         (when (> rest-len 0) (doin3 rest-elem do-fn))))  
;assume that the calculate is a time-consumed operation  
(defn calculate [v x1 x2 x3]   
    (conj v (+ x1 x2 x3)))  
(doin3 large-number-list #(send result calculate %1 %2 %3))  
(println "before await")  
(await result)  
(println "after await")  
(println @result)  
(def total (apply + result))  
(println "total is:" total)  
(shutdown-agents)   

预期产出:

x1 x2 x3 1 2 3  
rest-len is  9  
x1 x2 x3 4 5 6  
rest-len is  6  
x1 x2 x3 7 8 9  
rest-len is  3  
x1 x2 x3 10 11 12  
rest-len is  0  
before await  
after await  
total is: 78  

实际输出:

x1 x2 x3 1 2 3  
rest-len is  9  
x1 x2 x3 4 5 6  
rest-len is  6  
x1 x2 x3 7 8 9  
rest-len is  3  
x1 x2 x3 10 11 12  
rest-len is  0  
before await  

问题:
代码运行到“等待之前”并阻止,我想代理中的操作没有完成,但为什么呢? 请告诉我我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

我认为问题在于这一行:

(def total (apply + result))

应该是:

(def total (apply + @result))

它实际上并没有阻止,而是抛出异常。

还有一点需要注意:您应该考虑在recur中使用doin3,而不是直接调用,因为它已处于尾部位置。