oxal.org

~/blog $ cat simple-clojure-state-machine.md

Simple state machine in Clojure

Mitesh aka ox 192 words · ~1 min #programming

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?

EOF

guest@ark: ~/blogzsh

$ whoami

Mitesh's photo

Mitesh Shah, aka oxalorg. I build things in Mumbai and write some of them down here.

$ rant --at

Did I waste your time? Come tell me about it. Or mail mitesh@oxal.org.

$ subscribe --rate "2 emails/year"

Plain-text life updates, no bullshit. Drop your email here, or follow the atom feed.