Sunday, 2 March 2014

Recursion

Sometimes in life, we have to do very repetitive tasks. We may have to apply the same operation to a number for an unspecified number of times until we get a result we like, or we may have to create a complex data structure comprised of many instances of a simpler data structure. We may have to search through a complex set of data, infinitely large, one piece at a time. We may to write blog posts we don't really want to write. All of the above can be very time-consuming, headache-inducing tasks when tackled with brute force; fortunately, for all except the latter, there is a simple and elegant solution, and that solution is recursion.

Recursion is basically the use of a method or operation that is defined in terms of itself, allowing the same method to be repeated indefinitely, storing the result of each iteration along the way until an end condition is met (hopefully). This allows very complicated data structures to be initiated and traversed with very few lines of code. For example, large trees and linked lists are really just made of smaller trees and linked lists, and can be traversed by repeating the function 'search self then search children,' which will be repeated until the end of the data structure. Many mathematical sequences and series can also be defined recursively; the integer set can be defined as a set that starts at 0, and every subsequent term is just the previous term + 1. Arithmetic and geometric series can also be easily defined, by adding or multiplying each term to get the subsequent term; geometric series are very useful IRL for calculating chance and probability, and arithmetic series are useful for filtering through orderly sets of data like a spreadsheet arranged in rows, with the results of each trial following the previous trial.

There are of course countless uses for recursion that I cannot discuss or have yet to realize. The true power of recursion lies in its ability to break down a complex problem into many iterations of smaller problem. Understanding recursion will allow us to easily solve the problems that lie before us, opening the door for even more complex problems and solutions. I will remember recursion as a very useful tool going forward, and I look forward to discovering better ways to make use of it.

No comments:

Post a Comment