Slightly Easier Recursive Functions

I've joked before that recursive functions were the kind that make you "curse over and over and over and over...". Granted, they aren't the most difficult thing to do in programming, they can tend to require a little more focus to write correctly.

So when you work with a recursive function you normally need to create some sort of safety counter to prevent an infinite loop. If not you end up passing around your counter by reference which can be a bit confusing to developers in itself.

Not only that, it also tends to hurt the "black box" approach to class design. Even if the method is private you still need to prepare a safety counter in advance before you can call the method -- a function that has a order dependency, which isn't a good thing.

Lambda To The Rescue

I love working with lambdas - I think that I cried a tear of joy the day I realized they could be passed as an argument (actually, I didn't... that would be weird).

So what if we created a single lambda within our functions that would perform all of the recursive logic inline?

public void ScanElements(XElement xml) {

    //create a safety counter
    int safety = 0;

    //declare the scan action as null at first
    //since we can't call it recursively inside
    //the method unless it is declared first
    Action<XElement> scan = null;

    //assign the actual work to do
    scan = (node) => {

        //increment the safety
        if (safety++ >= 100) { return; }

        //do the actual work here

        //and then recursively call the scan method again
        foreach (XElement element in node.Elements()) {

        //reverse the safety


    //now, actually start the recursive function here


Now, that isn't too bad. We have all of our logic encapsulated into a single method that doesn't require any setup before it is used. It might be a little odd to a developer that hasn't used lambdas much, but a comment explaining what is going on should be enough to get them onto the right track.

Maybe this is a terrible idea - I'm not really sure but it does decrease complexity and improve encapsulation -- even if it is with a single private method.

Using the .Descendants() method as part of the XElement/XDocument classes would be much wiser here - this code is just an example of performing a recursive method.

September 24, 2009

Slightly Easier Recursive Functions

Using a local anonymous function to perform recursive calls.