Clojure参考项目最新? [英] Clojure reference Project up to date?

查看:169
本文介绍了Clojure参考项目最新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Clojure开始我发现了一个Rich Hickey的演讲,他在一个基本的 Ant-模拟器

Starting with Clojure I discovered a talk by Rich Hickey where he demonstrates some of Clojure's strengths on a basic Ant-Simulator.

这个代码仍然是Clojure的好参考吗?特别是当他递归地向代理发送函数以模拟游戏循环时的部分。
例如:

Can this code still be considered as a good reference for Clojure? Especially the parts when he recursively sends off functions to agents to simulate a game loop. Example:

(defn animation [x]
  (when b/running
    (send-off *agent* #'animation))
    (. panel (repaint))
  (. Thread (sleep defs/animation-sleep-ms))
  nil)

编辑

#'读取器宏不感兴趣,但更多的是它是惯用的/好Clojure到
递归调用代理上的函数。

I am not interested in the #' reader macro but more wether it is idiomatic/good Clojure to recursively call a function on a agent or not.

推荐答案

这个片段在Clojure 1.4中是最新的。函数是否习惯于将任务提交给调用它的代理?是的。

This snippet is current in Clojure 1.4. Is it idiomatic for a function to submit a task back to the agent that called it? Yes.

下面是一个使用类似方法递归计算阶乘的示例:

Here is an example that uses a similar approach to recursively calculate a factorial:

(defn fac [n limit total]
  (if (< n limit)
    (let [next-n (inc n)]
       (send-off *agent* fac limit (* total next-n)) 
       next-n)
     total))

 (def a (agent 1))

 (await (send-off a fac 5 1))
 ; => nil
 @a
 ;=> 120

更新

上面是一个假设的例子,实际上不是一个好的,因为在各种递归发送调用和后来 await 。可能有一些发送呼叫尚未添加到座席的任务队列。

The above is a contrived example and actually not a good one, as there is a race condition between the various recursive send-off calls and the later await. There may be some send-off calls yet to be added to the agent's task queue.

我重写上述内容如下:

(defn factorial-using-agent-recursive [x]
  (let [a (agent 1)]
    (letfn [(calc  [n limit total]
               (if (< n limit)
                 (let [next-n (inc n)]
                   (send-off *agent* calc limit (* total next-n))
                   next-n)
                 total))]
      (await (send-off a calc x 1)))
    @a))

并观察到以下行为:

user=> (for [x (range 10)] (factorial-using-agent-recursive 5))
(2 4 3 120 2 120 120 120 120 2)
user=> (for [x (range 10)] (factorial-using-agent-recursive 5))
(2 2 2 3 2 2 3 2 120 2)
user=> (for [x (range 10)] (factorial-using-agent-recursive 5))
(120 120 120 120 120 120 120 120 120 120)

故事的道德是:不要使用代理进行同步计算。将它们用于异步独立任务 - 例如更新显示给用户的动画:)

Moral of the story is: don't use agents for synchronous calculations. Use them for asynchronous independent tasks - like updating animations displayed to a user :)

这篇关于Clojure参考项目最新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆