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

后端 未结 11 1692
南笙
南笙 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:18

    In Haskell, the idiom for this is just to go ahead and execute the next state:

    type StateMachine = IO ()
    a, b, c :: StateMachine
    a = print "a()" >> b
    b = print "b()" >> c
    c = print "c()" >> a
    

    You need not worry that this will overflow a stack or anything like that. If you insist on having states, then you should make the data type more explicit:

    data PossibleStates = A | B | C
    type StateMachine = PossibleStates -> IO PossibleStates
    machine A = print "a()" >> return B
    machine B = print "b()" >> return C
    machine C = print "c()" >> return A
    

    You can then get compiler warnings about any StateMachine that forgot some states.

提交回复
热议问题