pure generators

Pelle pelle.mansson at gmail.com
Thu May 13 01:43:42 PDT 2010


On 05/13/2010 01:46 AM, bearophile wrote:
> The meaning of that little Haskell program is simple:
> fibonacci is a symbol, it can be seen as a lazy generator that yields a list of numbers. The first and second are 1 (the colon stands for list item concatenation), to it concatenates the zipping between the result of the generator and another "copy" of the same generator minus the first item.
>

It is stored as a list, and is in effect memoized. That's why it's a 
viable solution for haskell, and sucks in python.

You can, naturally, create the same in D. It will be more verbose, though.

...So I did.

struct Fibs {
     immutable(int)[] m = [0, 1];

     int front() { return m[$-1]; }

     void popFront() {
         m ~= m[$-2] + m[$-1];
     }
     enum bool empty = false;

     int opIndex(size_t a) {
         a += 1;
         while (a >= m.length) popFront;
         return m[a];
     }
}
Fibs fibonacchi;

That should be about the same. :)


More information about the Digitalmars-d mailing list