Sunday, 8 February 2015

SLOG Week 5 - Tracing recursion

Recursion is similar to using helper functions. In both cases, you use a function to accomplish part of the main function's task. The difference is that a recursive function is its own helper function. Obviously this could cause an infinite loop, so the recursive function must be designed so that it will eventually not call itself again - that is, it can figure out the return value on its own. This is the base case.

In the examples we've worked on, this takes the form of an if-else statement, where we check to see if this is the base case (in several examples, the base case was when the input value was not a list), then return something simple - the input value, or a specific int if we are counting something.

Tracing recursion is a way to understand recursion for humans. By working out what a function does for the base case and simple cases, we know we can trust the function for these cases, allowing us to quickly work out what the function does for more complicated cases.

No comments:

Post a Comment