Created
May 27, 2017 13:28
-
-
Save fmnoise/3e031f2741181872a8f07ec2b544d1a8 to your computer and use it in GitHub Desktop.
Moore machine macro
This file contains 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
(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