On 20 May 2010 11:42, Anders Rune Jensen <[email protected]> wrote:
> The algorithm:
>
> (defn change-state [cur-state]
> (when (> (:value cur-state) 10)
> (assoc cur-state :message "danger, danger")))
>
> How I'd have to write it when using an agent:
>
> (defn change-state [cur-state]
> (cond (> (:value cur-state) 10)
> (assoc cur-state :message "danger, danger")
> :else cur-state))
In this example, you could also have written your function using 'if',
which is not much more complex than your original definition using
'when':
(defn change-state [cur-state]
(if (> (:value cur-state) 10)
(assoc cur-state :message "danger, danger")
cur-state))
Of course, like you already said, this is a trivial example, but it
shows an important fact about agent actions: They don't modify state.
Instead, action functions just take a value (which just happens to be
the agents current state) and return a value (which just happens to
become the agents new state). Incidentally, for this reason you can
also use built-in primitive functions like 'assoc' or 'merge' as agent
actions, with no changes required. So, once you start focusing on
writing a function that returns the value you want, instead of
worrying about state change, chances are that you'll have less trouble
with nil values ending up in the agent's state.
Disclaimer: This mental approach worked for me. YMMV :-)
--
Daniel
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en