How would one implement Lazy Evaluation in C?

后端 未结 9 1984
野的像风
野的像风 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:48

    As Will mentioned, languages like python do the job of storing the state of the stack between successive calls of the generator. Since C does not have this mechanism, you'll have to do it yourself. The "generic" way of doing this is not for the faint-hearted, as Greg pointed out. The traditional C way of doing this would be for you to define and maintain the state yourself and pass it in and out of your method. So:

    struct multiples_of_two_state {
           int i;
           /* all the state you need should go in here */
    };
    
    void multiples_of_two_init(struct multiples_of_two_state *s) {
        s->i = 0;
    }
    
    int multiples_of_two_next(struct multiples_of_two_state *s) {
        s->i += 2;
        return s->i;
    }
    
    /* Usage */
    struct multiples_of_two_state s;
    int result;
    multiples_of_two_init(&s);
    for (int i=0; i

提交回复
热议问题