How would one implement Lazy Evaluation in C?

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

    The basic approach is to not do it. In Python (and C#) the 'yield' method stores local state between calls, whereas in C/C++ and most other languages the local state stored on the stack is not preserved between calls and this is a fundemental implementation difference. So in C you'd have to store the state between calls in some variable explicitly - either a global variable or a function parameter to your sequence generator. So either:

    int multiples_of_2() {
       static int i = 0;
       i += 2;
       return i;
    }
    

    or

    int multiples_of_2(int i) {
       i += 2;
       return i;
    }
    

    depending upon if there's one global sequence or many.

    I've quickly considered longjmp and GCC computed gotos and other non-standard things, and I can't say I'd recommend any of them for this! In C, do it the C way.

提交回复
热议问题