Take for example,
The follow python code:
def multiples_of_2():
i = 0
while True:
i = i + 2
yield i
How do we translate this into C code?
Edit: I am looking to translate this python code into a similar generator in C, with next() function. What I am not looking for is how to create a function in C to output multiples of 2. Multiples of 2 is merely an example to illustrate the problem of lazy eval generators in C.
To implement lazy evaluation in our interpreter we need to modify the applica- tion expression evaluation rule to delay evaluating the operand expressions until they are needed. To do this, we introduce a new datatype known as a thunk. We define a Python class, Thunk for representing thunks.
Yes, in C++ short circuit and and or operators are available. Here's a question answered in the C-faq on the subject. Show activity on this post.
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing).
Lazy evaluation or call-by-need is a evaluation strategy where an expression isn't evaluated until its first use i.e to postpone the evaluation till its demanded. Functional programming languages like Haskell use this strategy extensively.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With