by thinkpad20 · 12y ago · 0 comments
Clojure tends to view mutability as a concurrency problem, and the tools it provides to deal with mutability, such as atoms, refs, agents, channels and so forth, are not mechanisms to avoid mutation, as to provide various guarantees that restrict it in some fashion.
It might be that in the cases where I'd use a state monad in Haskell, in Clojure I might instead use an atom. They're in no way equivalent, but they have some overlapping use-cases.
(-> state
(assoc :a val)
(update-in [:b :c] f args)
(dissoc :d)
(some-other-fn args))
where :a - :d are keys.Or you could use monads in much the same way as you would in Haskell; there are libs for that.
Or you could write a new macro (or maybe even function) that does exactly what you want. I did that for a game. It looked like this:
(call-update-fns game-state hook
(update-monster-positions)
(update-monster-ai)
(let-characters-attack)
(some-other-stuff))
It would thread the game-state (immutable) through all the functions, and call hook (a function) in between all the functions to send network messages and stuff (to minimize latency), and also collect and return new events that the functions created that I needed to handle (e.g. someone died when the characters attacked). It's almost like the state monad but not quite. (-> {:a 1 :b 2}
(->/assoc :a inc)
(->/as {:keys [b]}
(->/when (> b 10)
(->/assoc :large-b true))))
1: https://github.com/LonoCloud/synthread