Skip to content

Instantly share code, notes, and snippets.

@AlexBaranosky
Created March 29, 2012 04:36
Show Gist options
  • Save AlexBaranosky/2233328 to your computer and use it in GitHub Desktop.
Save AlexBaranosky/2233328 to your computer and use it in GitHub Desktop.
state monad as a way to hold 'world' state
(defmacro defworld [name bindings & body]
`(defn ~name ~bindings
(fn [~'world]
(println ~'world)
~@body)))
(defmacro with-world [& body]
`(domonad state-m
~@body))
(defworld inc-w [population]
[(inc population) (update-in world [:peons] conj :a-peon)])
(defworld double-w [population]
[(* 2 population) (update-in world [:peons] concat (:peons world))])
(defworld dec-w [population]
[(dec population) (update-in world [:peons] rest)])
(defn alter-population [starting-world]
(let [initial-population (count (:peons starting-world))
state-fn (with-world [a (inc-w initial-population)
b (double-w a)
c (dec-w b)
d (dec-w c)]
d)]
(state-fn starting-world)))
(fact
(alter-population {:peons [:a-peon :a-peon :a-peon]})
=> [6 {:peons [:a-peon :a-peon :a-peon :a-peon :a-peon :a-peon]}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment