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

后端 未结 11 1691
南笙
南笙 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 the C-like type systems functions are not first order citizens. There are certain restrictions on handling them. That was a decision for simplicity and speed of implementation/execution that stuck. To have functions behave like objects, one generally requires support for closures. Those however are not naturally supported by mosts processors' instruction sets. As C was designed to be close to the metal, there was no support for them.

    When declaring recursive structures in C, the type must be fully expandable. A consequence of this is, that you can only have pointers as self-references in struct declarations:

    struct rec;
    struct rec {
        struct rec *next;
    };
    

    Also every identifier we use has to be declared. One of the restrictions of function-types is, that one can not forward declare them.

    A state machine in C usually works by making a mapping from integers to functions, either in a switch statement or in a jump table:

    typedef int (*func_t)();
    
    void run() {
        func_t table[] = {a, b, c};
    
        int state = 0;
    
        while(True) {
            state = table[state]();
        }
    }
    

    Alternatively you could profile your Python code and try to find out why your code is slow. You can port the critical parts to C/C++ and keep using Python for the state machine.

提交回复
热议问题