Traditional recursion
If you're like me, when it has come to writing a recursive algorithm, you generally follow the pattern of defining a function that contains all the code that needs to be executed repeatedly and then call this from another function. It's simple and it works, but it does require that you create at least two functions. Let's take a look at an example where recursion is used to calculate the factorial for a given number:
public void TraditionalRecursion() { Console.WriteLine(ComputeFactorial(5)); } private int ComputeFactorial(int n) { if (n == 0) { return 1; } return (n * ComputeFactorial(n - 1)); }
The "work" is being done by the ComputeFactorial function, but as it needs to be able to call itself, it has to be created as a separate function. Like with many recursive algorithms, the first function (TraditionalRecursion) doesn't contain any logic or functionality that requires it to be separated--it just has to act as the starting point for the algorithm.
Lambda recursion
Now, wouldn't it be nice if you could do this with just a single function where you no longer need a second function just to start the algorithm. Imagine being able to define the recursive algorithm and start it all within the same function. Well, it turns out that this is quite easily achievable through the use of a lambda expression:
public void LambdaRecursion() { Func<int, int> computeFactorial = (n) => { if (n == 0) { return 1; } return n * ComputeFactorial(n - 1); }; Console.WriteLine(computeFactorial(5)); }
The inline delegate, a Func in this example, contains exactly the same behavior as the ComputeFactorial function; the only difference is that it has been declared as a variable. An easy way to look at this, is to image that ComputeFactorial has been wrapped up and is now contained within the computeFactorial variable (declaring functions as variables should be very familiar concept to a JavaScript programmer). Once declared, all you have to do it call this variable to start the recursive algorithm--it really is as simple as that!