generator functions in another language

Terry Reedy tjreedy at udel.edu
Sun May 4 23:24:13 EDT 2008


A 'generator function' -- a function that when called returns a generator 
object, a specific type of iterator,  is a rather Python specific concept. 
Better to think,  I think, in terms of writing an iterator 'class' (in C, 
struct with associated function).  Looking at the implementation of two of 
the itertools in the link below (previously posted), I could see the 
'template' that each was based on and that would be the basis for writing 
another.  (And I have not programmed C for a decade.  Raymond's code is 
quite clear.)

=================================
[Outlook Express does not 'quote' this post properly]

"Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> wrote in message 
news:op.uanmdnsrx6zn5v at a98gizw.cpe.telecentro.net.ar...

 The itertools module may be used as reference - "cycle" and "chain" are 
the easiest I think, although they might be *too* easy to understand the 
structure. "groupby" is a more complex example but at the same time harder 
to understand. See 
http://svn.python.org/projects/python/trunk/Modules/itertoolsmodule.c

Ok, I'll try to use Python code as an example. A generator for Fibonacci 
numbers:

def fibo():
     a = b = 1
     while True:
         a, b = b, a+b
         yield b

We can convert that function into this object; it should be written in C, 
not Python, but the idea is the same:

class fibo:
     def __init__(self):
         self.a = 1
         self.b = 1
     def next(self):
         temp = self.a + self.b
         self.a = self.b
         self.b = temp
         return temp
     def __iter__(self):
         return self

=============================
Terry again: one can think of a generator function as an abbreviation of an 
iterator class.  Calling the gen. func. produces an iterator instance just 
like calling the class object.
=============================
[back to Gabriel]
It behaves exactly the same as the generator above; we can even use the 
same code to test it:

py> for n in fibo():
...   if n>100: break
...   print n
...
2
3
5
8
13
21
34
55
89

Converting that class into C code should be straightforward. And then you 
have a generator-like function written in C.

==================================






More information about the Python-list mailing list