Skip to content

Instantly share code, notes, and snippets.

@timsgardner
Last active March 5, 2016 21:39
Show Gist options
  • Save timsgardner/9aa17ed1123a9f4b4755 to your computer and use it in GitHub Desktop.
Save timsgardner/9aa17ed1123a9f4b4755 to your computer and use it in GitHub Desktop.
robot thing
(defprotocol IRobot ; ha
(live? [_])
(kill [_])
(state [_]))
(defn robot
([state f]
(robot state (constantly true) f))
([state continue? f]
(let [kill (a/chan (a/sliding-buffer 1))
live (volatile! true)
state-v (volatile! state)
rt (a/go-loop []
(let [state @state-v]
(if (or (not (continue? state)) (a/poll! kill))
(vreset! live false)
(do (vreset! state-v (f state))
(recur)))))]
(reify IRobot
(live? [_] @live)
(kill [_] (when-not @live (a/go (a/>! kill true) true)))
(state [_] @state-v)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment