Clean and type-safe state machine implementation in a statically typed language?

后端 未结 11 1695
南笙
南笙 2021-02-01 04:26

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         


        
11条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 05:24

    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.

提交回复
热议问题