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

后端 未结 11 1690
南笙
南笙 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-01 05:29

    You can get the same effect in C as in Python code,- just declare that functions return (void*):

    #include "stdio.h"
    
    typedef void* (*myFunc)(void);
    
    void* a(void);
    void* b(void);
    void* c(void);
    
    void* a(void) {
        printf("a()\n");
        return b;
    }
    
    void* b(void) {
        printf("b()\n");
        return c;
    }
    
    void* c(void) {
        printf("c()\n");
        return a;
    }
    
    void main() {
        void* state = a;
        while (1) {
            state = ((myFunc)state)();
            sleep(1);
        }
    }
    

提交回复
热议问题