Monday, August 23, 2010

C# - Fibonacci and lambda expression using Func Delegate

All of us who deal with C# in day to day life must have come across Func<T, TResult> Delegate many times, where T is the type of the parameter of the method and TResult the type of the return value of the method that this delegate encapsulates.

Lets try using Func on the Fibonacci squence.
Fibonacci sequence is a sequence of the numbers where the next number is found by adding up the two numbers before it.
eg.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

  • 2 is found by adding the two numbers before it(1+1)
  • 3 is found by adding the two numbers before it(1+2)

This Fibonacci Sequence can be written as a "Rule" :
                                 The Rule is xn = xn-1 + xn-2

where:
  • xn is term number "n"
  • xn-1 is the previous term (n-1)
  • xn-2 is the term before that (n-2)
There are many ways we can write the "Fibonacci" in C#:

A.
public static int Fibonacci(int n)
        {
            int previous = -1;
            int result = 1;
            for (int i = 0; i <= n; i++)
            {
                int sum = result + previous;
                previous = result;
                result = sum;
            }
            return result;
        }
B.
static int Fibonacci (int x)
{
   if (x <= 1)
      return 1;
   return Fibonacci (x-1) + Fibonacci (x-2);
}
C. Using the .Net 3.5 we can wirte this using Func

 static void Main()
{
    Func<int, int> fib = null;
           fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

        Console.WriteLine(fib.Invoke(10));
}

Other example of Func :
static void Main()
{
    Func<int, string> funcTest = (x) => string.Format("String is = {0}", x);
}

No comments:

Post a Comment