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
- xn is term number "n"
- xn-1 is the previous term (n-1)
- xn-2 is the term before that (n-2)
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{
if (x <= 1)
return 1;
return Fibonacci (x-1) + Fibonacci (x-2);
}
static void Main()
{
Func<int, int> fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
Console.WriteLine(fib.Invoke(10));
}
{
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