Thursday, 5 February 2015

Wrapping my head around recursion

I now know that recursion is when you call the method you are using inside of that method. It's a very useful technique that saves a lot of time and prevents a lot of repetitive coding.

So it's simple right? All you have to do is call method A inside of method A and then... wait a minute. How can I use method A inside of method A if I 'm not done with my original instance of method A? That would be like starting to eat a cake, finding the exact same cake inside of it, eating that inside cake but then finishing the outside cake... which happens to be the exact same cake as the one you just ate.
I can have my cake inside a cake and eat it too!
Or at least those were the first thoughts that went through my mind when I heard the definition of recursion (possibly excluding the cake metaphor). However, I soon learned that my mindset was on the wrong track.
A depiction of my train of thought at the time.
What I failed to realize at the start is that, if the method does not call it's recursion it returns an actual value. Therefore, when a method undergo's recursion it simply continues to narrow down the scope of the input until it eliminates the need to undergo further recursion. It then returns that value to previous instance of that method. It continues this process until it once again reaches the main instance of the method and can undergo no more recursions.

Despite the very logical explanation behind how recursion works I will continue to feel like a wizard every time I utilize it and so will Google employees when they're not too busy confusing web surfers with logic jokes.

Oh Google, you sly dog...

1 comment: