I implemented a simple state machine in Python:
import time
def a():
print \"a()\"
return b
def b():
print \"b()\"
return c
def c():
print
Iit's not hard to make state machines in Haskell, once you realize that they are not monads! A state machine like the one you want is an arrow, an automaton arrow to be exact:
newtype State a b = State (a -> (b, State a b))
This is a function, which takes an input value and produces an output value along with a new version of itself. This is not a monad, because you cannot write join
or (>>=)
for it. Equivalently once you have turned this into an arrow you will realize that it's impossible to write an ArrowApply
instance for it.
Here are the instances:
import Control.Arrow
import Control.Category
import Prelude hiding ((.), id)
instance Category State where
id = State $ \x -> (x, id)
State f . State g =
State $ \x ->
let (y, s2) = g x
(z, s1) = f y
in (z, s1 . s2)
instance Arrow State where
arr f = let s = State $ \x -> (f x, s) in s
first (State f) =
State $ \(x1, x2) ->
let (y1, s) = f x1
in ((y1, x2), first s)
Have fun.