How would one implement Lazy Evaluation in C?

后端 未结 9 1986
野的像风
野的像风 2021-02-02 13:24

Take for example,

The follow python code:

def multiples_of_2():
  i = 0
  while True:
    i = i + 2
    yield i

How do we translate thi

9条回答
  •  情深已故
    2021-02-02 13:59

    You could try to encapsulate this in a struct:

    typedef struct s_generator {
        int current;
        int (*func)(int);
    } generator;
    
    int next(generator* gen) {
        int result = gen->current;
        gen->current = (gen->func)(gen->current);
        return result;
    }
    

    Then you define you multiples with:

    int next_multiple(int current) { return 2 + current; }
    generator multiples_of_2 = {0, next_multiple};
    

    You get the next multiple by calling

    next(&multiples_of_2);
    

提交回复
热议问题