Search code examples
dlazy-evaluation

infinite Datastructures in D


I found examples of lazy evaluation of function arguments in D http://www.digitalmars.com/d/2.0/lazy-evaluation.html

I´m wondering how to implement possible infinite Datastructures in D like it´s common behaviour of haskell´s lists.

Are there some Examples ?

What is the equivalent of the infinite fibonacci sequence:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

Solution

  • check out how randoms are implemented for an example https://github.com/D-Programming-Language/phobos/blob/master/std/random.d

    but here's the fibonacci sequence

    struct FiboRange{
        enum bool empty=false;//infinite range
    
        long prev=0,curr=1;//the state for next calculations
    
        @property long front(){
            return curr;//current value
        }
    
        void popFront(){//calculate the next value
            long tmp = curr;
            curr += prev;
            prev = tmp;
        }
    
    }