Saturday, 7 March 2015

Recursion, thoughts

If it is good to do it once, doing it again must be better right? Hence the efficacy of recursion. I always wondered how to travel down a path when you don't know where it stops. It reminds me of the excitement when I was a child in wondering into a forrest or a field with no idea where it was taking me but I knew would lead me to someplace interesting. I liken recursion to getting to that interesting place.

Of course there is an imminently practical need for recursion. I come across it a lot in my day job, the need to fit everything into a pre-defined box whether it makes sense or not. How do you draw the box if you don't now how big or what shape the box is? It is nice that in programming there is a way to resolve this problem.

The key element to make this work is defining the correct base case. In learning this construct I spent a lot of time hitting the escape button while my little program went into an infinite loop. Not unlike when I started using where clauses (I still mess these up more than I care to admit). I think the key is knowing when to use recursion and when too much of something isn't necessarily a good thing (see opening statement).

As in all things it is important to know when it applies. Dealing with aggregated data is always problematic. Recursion is a great solution in dealing with data that is in a ragged hierarchy where base data is at different depths (how many levels of summation are required). One approach is to convert all of the data to the same structure. Not ideal but it is the most common approach I see. I like that recursion can remove this very painful step.

The most difficult part at the outset was determine when recursion was the right solution. I have a tendency to try to apply a new concept to everything. It is my way of determine the boundaries of a particular approach. I wrote quite a few instances of recursive silliness in the process. I think I have the handle on it now but I know there will be many instances of wrongly applied recursion in my future. I like the idea of drawing a picture of what I need from a program before I start typing. This seems to mitigate choosing the wrong programming construct.

So my conclusion on recursion, it is a great solution to many problems but make sure you draw a picture first!




No comments:

Post a Comment