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

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

    Your problem has been had before: Recursive declaration of function pointer in C

    C++ operator overloading can be used to hide the mechanics of what is essentially the same as your your C and Haskell solutions, as Herb Sutter describes in GotW #57: Recursive Declarations.

    struct FuncPtr_;
    typedef FuncPtr_ (*FuncPtr)();
    
    struct FuncPtr_
    {
      FuncPtr_( FuncPtr pp ) : p( pp ) { }
      operator FuncPtr() { return p; }
      FuncPtr p;
    };
    
    FuncPtr_ f() { return f; } // natural return syntax
    
    int main()
    {
      FuncPtr p = f();  // natural usage syntax
      p();
    }
    

    But this business with functions will, in all likelihood, perform worse than the equivalent with numeric states. You should use a switch statement or a state table, because what you really want in this situation is a structured semantic equivalent to goto.

提交回复
热议问题