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.

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

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]).

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

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 feedback and consider subscribing to the RSS feed. You can also subscribe to it by email. Also, you can follow me on Twitter. Thank you!

Comments are closed