Starting with Clojure I discovered a talk by Rich Hickey where he demonstrates some of Clojure’s strengths on a basic Ant-Simulator.
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)
Edit:
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.
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:
Update
The above is a contrived example and actually not a good one, as there is a race condition between the various recursive
send-offcalls and the laterawait. There may be somesend-offcalls yet to be added to the agent’s task queue.I re-wrote the above as follows:
and observed the following behavior:
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 🙂