KIM*_*IMA 12 d lazy-evaluation
我在D http://www.digitalmars.com/d/2.0/lazy-evaluation.html中找到了函数参数的延迟评估示例
我想知道如何在D中实现可能的无限数据结构,就像它是haskell列表的常见行为一样.
有一些例子吗?
无限斐波那契数列的等价物是什么:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
Run Code Online (Sandbox Code Playgroud)
Meh*_*dad 11
recurrence!((s,n) { return s[n-1] + s[n-2]; })(0, 1)
Run Code Online (Sandbox Code Playgroud)
rat*_*eak 10
查看如何实现randoms的示例https://github.com/D-Programming-Language/phobos/blob/master/std/random.d
但这是斐波那契序列
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Arlen在评论中提到D版本很快就会溢出,因为它没有使用bigints.幸运的是,bigints可用作库模块,并且兼容recurrence:
import std.bigint;
auto fibs = recurrence!"a[n-1] + a[n-2]"(BigInt(1), BigInt(1));
Run Code Online (Sandbox Code Playgroud)
这与Mehrdad的答案基本相同,但在我看来,它使用的语法稍微更具可读性:
recurrence!"a[n-1] + a[n-2]"(1, 1)
Run Code Online (Sandbox Code Playgroud)