Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would one implement Lazy Evaluation in C?

Tags:

python

c

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.

like image 422
nubela Avatar asked Oct 28 '09 08:10

nubela


People also ask

How is lazy evaluation implemented?

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.

Does C do lazy evaluation?

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.

How does lazy evaluation work?

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).

Which of the following is a lazy evaluation operator?

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.


1 Answers

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);
like image 180
jdb Avatar answered Oct 14 '22 23:10

jdb