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 >
{
int f0, f1;
int operator()();
}

int fibonacchi::operator()()
{
DECLARE_GEN1( state1 );
f0 = 1;
f1 = 1;
while( true ){
YIELD;
int f2 = f0 + f1;
f0 = f1;
f1 = f2;
}
END_GENERATOR;
return -1; //Dummy return to suppress warning.
}

//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