Skip to content

Instantly share code, notes, and snippets.

@fmnoise
Created May 27, 2017 13:28
Show Gist options
  • Save fmnoise/3e031f2741181872a8f07ec2b544d1a8 to your computer and use it in GitHub Desktop.
Save fmnoise/3e031f2741181872a8f07ec2b544d1a8 to your computer and use it in GitHub Desktop.
Moore machine macro
(ns machines.moore)
(defn make-state-fn [& states]
(let [statemap
(zipmap
(map str states)
(rest (conj (vec states) (first states))))]
(fn [state] (statemap (str state)))))
(defmacro make-moore-machine
[& states]
`(let [state# (atom (first '~states))
map# (make-state-fn ~@states)]
(fn [& _] (swap! state# map#))))
(def machine (make-moore-machine :stopped :starting :started :stopping))
;; all params are ignored
(machine "foobar" 123) ; :starting
(machine) ; :started
(machine) ; :stopping
(machine) ; :stopped
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment