Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 324
KIMA Avatar asked Jun 28 '11 20:06

KIMA


2 Answers

recurrence!((s,n) { return s[n-1] + s[n-2]; })(0, 1)
like image 172
user541686 Avatar answered Jan 01 '23 07:01

user541686


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;
    }

}
like image 27
ratchet freak Avatar answered Jan 01 '23 08:01

ratchet freak