Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerators in C
    primarykey
    data
    text
    <p>I got this chunk of code I can't really comprehend.</p> <p>I got stuck after it replaced pow2s's g to a map's gen structure. And from there, I can't see how it continues tracking the value, and how it is stored.</p> <p>The code compiles and runs.</p> <p>Can someone help me understand this code? Thanks!</p> <p>PS: I'm learning C</p> <p>It is translated from the follow Python code:</p> <pre><code>&gt;&gt;&gt; def pow2s(): yield 1 for i in map((lambda x:2*x),pow2s()): yield i &gt;&gt;&gt; def mymap(f,iter): for i in iter: yield f(i) </code></pre> <p>And the translated C code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; struct gen { // generic structure, the base of all generators int (*next)() ; int continue_from ; } ; typedef int (*fptr)() ; // Each iterator has 3 components: a structure, a constructor for the structure, // and a next function // map struct mapgen { // structure for map int (*next)() ; int continue_from ; // not really required, provided for compatibility fptr f ; struct gen *g ; } ; int map_next(struct mapgen *p) { // next function for map return p-&gt;f(p-&gt;g-&gt;next(p-&gt;g)) ; } struct gen *map(fptr f, struct gen *g) { // constructor for map iterator struct mapgen *p = (struct mapgen *)malloc(sizeof(struct mapgen)); p-&gt;next = map_next; p-&gt;continue_from = 0; p-&gt;f = f; p-&gt;g = g; return (struct gen *)p ; } // powers of 2 struct pow2s { // structure int (*next)() ; int continue_from ; struct gen *g ; }; int times2(int x) { // anonymous lambda is translated into this return 2*x ; } struct gen *pow2() ; // forward declaration of constructor int pow2next(struct pow2s * p){ // next function for iterator switch(p-&gt;continue_from) { case 0: p-&gt;continue_from = 1; return 1; case 1: p-&gt;g = map(times2,pow2()) ; p-&gt;continue_from = 2; return p-&gt;g-&gt;next(p-&gt;g) ; case 2: p-&gt;continue_from = 2; return p-&gt;g-&gt;next(p-&gt;g) ; } } struct gen * pow2() { // constructor for pow2 struct pow2s * p = (struct pow2s *)malloc(sizeof(struct pow2s)); p-&gt;next = pow2next; p-&gt;continue_from = 0; return (struct gen *)p; } // in main, create an iterator and print some of its elements. int main() { int i ; struct gen * p = pow2() ; for(i=0;i&lt;10;i++) printf("%d ",p-&gt;next(p)) ; printf("\n"); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload