I've decided to try and write a simulation program in Clojure (as a proof of concept) where:
- The entire state of the simulation is stored in a single immutable data structure
- State updates are represented as functions that map a state to the next state
This means that I could write an update function as something like:
(defn example-update-function [old-state]
(let [state (atom old-state)]
(swap! state some-other-update-function-1)
(if (some-condition @state)
(swap! state some-conditional-update-function))
(swap! state some-other-update-function-2)
(reset! state (some-function @state some-other-param))
@state))
The approach seems to work but the following gives me two causes for concern:
- I'm having to use a mutable atom to manage the intermediate states... doesn't seem very functional!
- The code seems a bit ugly with all the swap!s and @state dereferences everywhere.
Is there a better / more elegant approach?
stateatom here, or why you're using an atom at all. Are the functions you're calling reading it somehow? - seh