Friday, April 3, 2009

Functional Fibonnaci series in C#

C# code for functional fibonnaci numbers

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

Okay so you guys would think why would i declare the delegate in one line and instantiate in the next. The reason is that if you do everything in same line complier wont recognize the recursive call using the delegate. Try this

Func<int, int> fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

Above code wont compile

Haskell code for same
fib n
| n == 0 = 0
| n == 1 = 1
| n > 1 = fib (n-1) + fib (n-2)

No comments:

Post a Comment