Skip to content

Instantly share code, notes, and snippets.

@selfsame
Created January 30, 2016 09:43
Show Gist options
  • Select an option

  • Save selfsame/be7b3d396247b19f3c54 to your computer and use it in GitHub Desktop.

Select an option

Save selfsame/be7b3d396247b19f3c54 to your computer and use it in GitHub Desktop.
(defmacro machine [sym args & body]
(let [gosym (symbol (str sym (hash sym)))
[state value] args
pre (take-while (comp not {'-> 1} first) body)
inputs (filter (comp {'-> 1} first) body)
chans (cons '_kill_ (map (comp first rest) inputs))
conds (map #(list '= 'c %) chans)
outputs (cons nil (map (comp first format rest rest) inputs))]
`(do
~@(map (fn [c] (concat ['def c] ['(chan (async/sliding-buffer 1))])) chans)
(~'def ~gosym nil)
(~'defn ~sym [initial#]
(try (~'close! ~gosym) ~'(catch js/Error e))
(~'set! ~gosym
(~'go
(loop [~state initial#]
~@pre
(~'let [[~value ~'c] (~'alts! [~@chans])]
(when ~value
(~'cond ~@(interleave conds outputs)))))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment