Skip to content
dmishin edited this page Sep 14, 2010 · 5 revisions

Here is a sample Python code, producing infinite list of Fibonacchi numbers and corresponding C++ code with pseudo-generator:


def fibonacchi():
    "Generator, yielding infinite list of fibonacchi numbers"
    f0 = 1
    f1 = 1
    while True:
         yield f0
         f0, f1 = f1, f0+f1

#Sample usage of the above generator:
#Printing all fibonacchi numbers below 1000
for f in fibonacchi():
     print f
     if f > 1000:
         break

C++ analog with pseudo_generator


#include "pseudo_generator.hpp"

struct fibonacchi: generator< int, fibonacchi > 
{
    int f0, f1; //Generator generally can't use local variables - using fields instead
    void operator()( int & value ); //main code
}

//Generating infinite sequence of the fibonacchi numbers
void fibonacchi::operator()( int & value )
{
    GENERATOR1 ( state1 );  //1 means generator with 1 state
    f0 = 1;
    f1 = 1;
    while( true ){
        YIELD ( value, f0, state1 );  
        int f2 = f0 + f1;
        f0 = f1;
        f1 = f2;
    }
    END_GENERATOR;
}

//Sample usage
int main( int argc, char* argv[] )
{
    using namespace std;
    fibonacchi gen;
    for( int x; gen >> x; ){
        cout << x << endl;
        if ( x > 1000 )
              break;
    }
    return 0;
}

Clone this wiki locally