HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Calculating Fibonnaci sequence lazily

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fibonnacicalculatinglazilysequence

Problem

Implementation:

IEnumerable Fibs()
{
    BigInteger a = 0;
    BigInteger b = 1;
    while(true)
    {
        b = a + (a = b);
        yield return a;
    }
}


Usage:

void Main()
{
    // take first 100 fib numbers
    var fibs = Fibs().Take(100);
}


How can I improve this?

Solution

That's a pretty clever implementation. To improve this, I would take some of the cleverness out of it. In particular:

while (true)
{
    BigInteger next = a + b;
    a = b;
    b = next;
    yield return next;
}


2 lines longer, but no unnecessary cleverness. Perfectly clear, nice and simple, and should be just as efficient. It's good general rule to not try to be too clever. Keep it simple.

Also, FibonacciSequence would be a better name than Fibs.

Finally, as a tiny remark, put a space before opening parenthese of the while condition (like I did above, different from the original code).

Code Snippets

while (true)
{
    BigInteger next = a + b;
    a = b;
    b = next;
    yield return next;
}

Context

StackExchange Code Review Q#66686, answer score: 11

Revisions (0)

No revisions yet.