Monday, December 15, 2008

Recursion

Recursion is one of those things self-taught programmers (or designers who dabble a bit in programming, like me) tend to overlook. That was certainly the case for me. Apart from the occasional situation where I needed to loop an indefinite number of times (and ended up cheating and using an iterative loop with an artificial end-point instead) I wasn't really aware of what it was.

But having realised it was something that I needed to get my head around, I rooted around on the web for a decent - and simple - tutorial.

(Those of you with a programming or mathematical background are probably laughing at the thought that it wouldn't be immediately obvious to anyone, but it took me a while to grasp the concept. However, once you do get it, its actually really straightforward. The key, for someone like me who generally writes very linear, one-dimensional code, is that you have to use a function to create a recursive loop - unless you want things to get extremely complicated!)

The test was to rewrite a piece of code I wrote a while back to display a nested list of web pages in a CMS. Previously I'd cheated by setting a limit on the number of nesting levels, but I wanted to allow an unlimited number.

In fact, the recursive version of the code is about 10 times simpler than the original iterative version and took me all of about 3 minutes to write - including thinking time!!

No comments: