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 th开发者_Go百科e equivalent of the infinite fibonacci sequence:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
recurrence!((s,n) { return s[n-1] + s[n-2]; })(0, 1)
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;
}
}
Arlen mentioned in a comment that the D version quickly overflows, because it doesn't use bigints. Fortunately, bigints are available as a library module, and are compatible with recurrence
:
import std.bigint;
auto fibs = recurrence!"a[n-1] + a[n-2]"(BigInt(1), BigInt(1));
This is basically the same thing as Mehrdad's answer but uses, in my opinion, slightly more readable syntax:
recurrence!"a[n-1] + a[n-2]"(1, 1)
ratchet freak covered Fib.
Because it is implemented as a value type, taking copies of it will act as expected. This will also work for any "data structure" (as the OP was using it, not a struct) of any size where a finite amount of storage and a transition operation can define the reachable domain from any point.
精彩评论