Monday, January 5, 2009

C# Yields a better Fibonacci Sequence

In the title of this blog entry I've done a bit of punning. This quick blog entry is about an alternate usage of the Yield command and how, for example, it can help build a better FibonacciSequence() function.

With the addition of the Yield command, we can now create looping functions that return a value for each iteration. Ever need to walk through a sequence and perform some fuction for each element? Now it is as easy as pie!

private IEnumerable FibonacciSequence(int MaxIterations)
{
decimal i = 0;
decimal j = 1;

while(true)
{
yield return j;
MaxIterations--;

if (MaxIterations==0) yield break;

var temp = (ulong) j;
j = temp+i;
i = temp;
}
}

private IEnumerable FibonacciSequence()
{
return FibonacciSequence(49);
}

No comments: