-
-
Save syou6162/2241779 to your computer and use it in GitHub Desktop.
state monad as a way to hold 'world' state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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