Infinite fibonacci sequence, lazy take first 42 values

Alain De Vos devosalain at ymail.com
Thu Apr 21 05:00:53 UTC 2022


On Thursday, 21 April 2022 at 04:36:13 UTC, Salih Dincer wrote:
> On Thursday, 21 April 2022 at 03:41:24 UTC, Ali Çehreli wrote:
>> On 4/20/22 19:11, Alain De Vos wrote:
>>
>> > Maybe there are multiple solutions ?
>>
>> Indeed. :)
>>
>> I have a Range struct here:
>>
>>   
>> http://ddili.org/ders/d.en/ranges.html#ix_ranges.infinite%20range
>>
>
> My favorite is the struct range.  Because it is more 
> understandable and personalized.  Moreover, you can limit it 
> without using ```take()```.
>
> ```d
> struct FibonacciRange(int l)
> {
>   long a = 1, b = 1;
>
>   bool empty()
>   {
>     return a > l;
>   }
>
>   long front() const
>   {
>    return a;
>   }
>
>   void popFront()
>   {
>     auto t = a;
>     a = b;
>     b += t;
>   }
> }
>
> enum limit = 16;
>
> void main()
> {
>   import std.stdio;
>   FibonacciRange!limit fibs;
>   fibs.write(": ");
>
>   import std.algorithm;
>   auto total = fibs.sum;
>   total.writeln;
>
>   assert(total == 33);
> }
> ```
> SDB at 79

This example limits the maximum value returned by the fibonacci 
function. f(n) < limit
But it does not allow to return the n-th element of a fibonacci 
function.


More information about the Digitalmars-d-learn mailing list