Week 7: Recursion
There is an assigned topic
for this week's slog: recursion! To begin, a simple definition of
recursion would be a situation where, in a function body, the
function itself is called. A function body, however, cannot contain
only recursive calls as this would lead to an endless recursion loop.
This problem is solved by having a base case, which is a piece of non
recursive code that the function implements under certain conditions.
Over the past four weeks
since recursion was introduced, the most common case I have seen in
which recursion is used is nesting. For example, the first recursive
function written in class was to find the sum of a nested list. Since
then, we have written more functions for nested lists, and have been
introduced to various other recursive structures. That includes
trees, linked lists, and search lists from the lab, which are
recursive because they may contain other instances of themselves
nested within them. Another case where recursion is used, and this is
where I was first introduced to the concept of recursion, is in a
mathematical function, where the result is dependent on the previous
result(s). For example, the week five reading mentioned the Fibonacci
sequence, and the function M(n) used to find the minimum number of
moves required for moving n number of cheeses from A1 use recursion.
Last, an additional use of recursion could be drawing pretty fractal
pictures.
When this topic was first
mentioned, I thought it was strange that the function could call
itself again without finishing its original call. But now I
understand that in order to finish the original call, the function
needs to call itself in order to solve the “sub-problem” and use
that result in finishing the first call. The first time I wrote
recursive function, I was overly concerned with my base case because
I was worried about the endless loop, but as I got more practice, I
was better able to write an effective solution with considerable
confidence and with a better understanding of how the function is
implemented. Also, I now see why this would be useful. For example,
in the case of nesting, it is much more simple and efficient to write
recursive code than to write non recursive code. That is because for
a large degree of nesting, one would need to write a large number of
repetitive code segments in order to deal with each degree of nesting
while writing a recursive call only would take up one line. Reading
that one line is also easier to understand than numerous lines of
repetition. Overall, I find recursion to be an interesting topic.
No comments:
Post a Comment