Simple state machine in Clojure
So I wanted to build a state machine for a multi-select component I am building in reagent (react wrapper for clojurescript).
I thought a bit about it and realised I should first start with the simplest possible state machine I can imagine.
This is the state transition diagram I drew up really quickly:
This is what I ended up with
(def transitions
{[:idle :run] :running
[:idle :jump] :jumping
[:running :stop] :idle
[:running :jump] :jumping
[:jumping :land] :idle
[:default :unknown] :idle})
(defn state-machine
[state! transitions]
(fn [event]
(let [next-state (get transitions [@state! event])]
(if next-state
(reset! state! next-state)
(throw (Exception. (str "Invalid transition: " event)))))))
(def state (atom :idle))
(def fsm (state-machine state transitions))
(fsm :run) ;; => :running
(fsm :jump) ;; => :jumping
(fsm :land) ;; => :idle
(fsm :run) ;; => :running
(fsm :stop) ;; => :idle
How would you improve this?