D Recurrences

Timon Gehr timon.gehr at gmx.ch
Thu Jun 9 08:51:53 PDT 2011


> On 6/9/11 10:32 AM, Ben Grabham wrote:
>> On 09/06/11 16:19, Ben Grabham wrote:
>>> Hey,
>>>
>>> Shouldn't both these programs output the fibonnacci numbers? Only the
>>> first one does.
>>>
>>> import std.range;
>>> import std.stdio;
>>> int main() {
>>> auto a = recurrence!("a[n-1] + a[n-2]")(0,1);
>>> int i = 0;
>>> foreach(int n; a) {
>>> if(i++ > 20) break;
>>> writefln("%d", n);
>>> }
>>> return 0;
>>> }
>>>
>>>
>>>
>>> import std.range;
>>> import std.stdio;
>>> int main() {
>>> auto a = recurrence!("a[n-1] + (n < 2 ? 0 : a[n-2])")(1);
>>> int i = 0;
>>> foreach(int n; a) {
>>> if(i++ > 20) break;
>>> writefln("%d", n);
>>> }
>>> return 0;
>>> }
>>
>> Also, is there a takeWhile function?
>> I can't find one in the documents...
>
> until?
>
> Andrei

until is not generic enough. It requires you to provide a dummy parameter if you
want to use an unary predicate. And you will have to reverse the predicate:
Thinking "while" is more convenient than thinking "until". Phobos should
definitely get a takeWhile function.

Timon


More information about the Digitalmars-d mailing list