# Recursion Applied using Delegates & Lambda Expressions

Yesterday, I came across an excellent article on *“Anonymous Recursion in C#” by Wesdyer*, I thought I’ll give a try on applying Delegates and Lambda Expressions in solving a recursive problem.

Lambda Expressions are well suited in solving mathematical problems (apart from other domains). One of the basic problem we encountered in our early mathematics is a factorial. A factorial is represented as **factoral(n) => n! = n(n-1)(n-2)!** where **factorial(0) = 1**. If you look at it, it is recursive by nature. We usually solve it using a recursive method in C# like this.

- /// <summary>
- /// Factorial is represented as n! = n(n-1)! or n! = n(n-1)(n-2)! so on...
- /// and you can see, it is recursive by nature.
- /// Also factorial of 0 is 1 [base case] i.e. Recursion limit/end condition.
- /// </summary>
- public static long Factorial(long n)
- {
- return n > 1 ? n * Factorial(n - 1) : 1;
- }
- }

Here is my take on it using a **generic and recursive delegate** and a **lambda expression**. (For functional programming and lambda calculas read here [Wiki]).

- delegate TResult RecursiveDelegate<TArg,TResult>( RecursiveDelegate<TArg,TResult> f, TArg arg );
- public static void FactorialTest()
- {
- RecursiveDelegate<long, long> factorial = (f, n) => n > 1 ? n * f(f, n - 1) : 1;
- // Look how I called the recursive delegate.
- Console.WriteLine(factorial(factorial, 5)); // The answer is 120.
- }

I defined a generic recursive delegate namely **RecursiveDelegate<TArg,TResult>**, that takes two arguments, one is reference to itself and the other one is, argument of generic type. The Factorial method, defined earlier, is re-written in the form of **Lambda Expression**, see Line#4 above. Also notice, how the recursion is invoked, line#7. Isn't it beautiful, absolutely is I’ll come to the **Lambda Expressions** once again when I’ll discuss about LINQ. So stay tuned.

If you enjoyed reading this blog, leave your valuable |