A simpler software state machine
Sunday, February 3rd, 2008Until recently, I had been running a software state machine which implemented a next-m-state function that took two arguments: m-state and i-state.
The i-state had not been an input state for quite some time. It is an instruction state, but it is redundant since it is pulled out of m-state.
So next-m-state was redone to accept only one argument, the m-state. The state machine becomes (slightly hacked because the base system does not have set!)…
swlsm =
(lambda (m-state-binding)
(loop
(set-cdr!
m-state-binding
(next-m-state (cdr m-state-binding))
)
)
)
The first stage extracts the instruction list and the environment…
next-m-state =
(lambda (m-state)
(execute (get-i-list m-state) (get-m-env m-state))
)
The second stage checks for the existence of instructions. If there is at least one instruction, the first instruction is split from the rest of the instruction list…
execute =
(lambda (i-list env)
(cond
((null? i-list) (exit))
(#t (exec1 (car i-list) (cdr i-list) env)
)
)
Finally, the instruction (also called a command, listed here as cmd) is executed…
exec1 =
(lambda (cmd next-i-list env)
(cond
((eq? (car cmd) (quote define)) (make-m-state
next-i-list
(quote ())
(add-to-env
(make-binding
(car(cdr cmd))
(eval (car(cdr(cdr cmd))) env)
)
env
)
)
)
(#t (make-m-state
next-i-list
(eval cmd env)
env
)
)
)
)