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
I have implemented my own lazy eval, with respects to solving the hamming's problem.
Heres my code for anyone whos interested:
#include
#include
// Hamming problem in C.
typedef struct gen {
int tracker;
int (*next)(struct gen *g);
} generator;
int twos_gen(struct gen *g) {
g->tracker = g->tracker + 2;
return g->tracker;
}
generator* twos_stream() {
generator *g = malloc(sizeof(generator));
g->next = twos_gen;
g->tracker = 0;
return g;
}
int threes_gen(struct gen *g) {
g->tracker = g->tracker + 3;
return g->tracker;
}
generator* threes_stream() {
generator *g = malloc(sizeof(generator));
g->next = threes_gen;
g->tracker = 0;
return g;
}
int fives_gen(struct gen *g) {
g->tracker = g->tracker + 5;
return g->tracker;
}
generator* fives_stream() {
generator *g = malloc(sizeof(generator));
g->next = fives_gen;
g->tracker = 0;
return g;
}
int smallest(int a, int b, int c) {
if (a < b) {
if (c < a) return c;
return a;
}
else {
if (c < b) return c;
return b;
}
}
int hamming_gen(struct gen *g) {
generator* twos = twos_stream();
generator* threes = threes_stream();
generator* fives = fives_stream();
int c2 = twos->next(twos);
int c3 = threes->next(threes);
int c5 = fives->next(fives);
while (c2 <= g->tracker) c2 = twos->next(twos);
while (c3 <= g->tracker) c3 = threes->next(threes);
while (c5 <= g->tracker) c5 = fives->next(fives);
g->tracker = smallest(c2,c3,c5);
return g->tracker;
}
generator* hammings_stream() {
generator *g = malloc(sizeof(generator));
g->next = hamming_gen;
g->tracker = 0;
return g;
}
int main() {
generator* hammings = hammings_stream();
int i = 0;
while (i<10) {
printf("Hamming No: %d\n",hammings->next(hammings));
i++;
}
}