Wednesday, December 3, 2014

C# Recursion with a Lambda

This is the first in a series about exploring the code patterns that Miguel Castro introduces in his Pluralsight course titled "Building End-to-End Multi-Client Service Oriented Applications". I am creating these blog posts as a learning exercise where I can delve deeper into the pattern and solidify my understanding of it. Hopefully this can be of some help to other programmers who are also taking Miguel's course or anyone trying to improve their C# skills.

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!