At first it did not make any sense to me, since the function seems to be put into use before it is completely defined, i.e. you are already calling the function before you even finish the last line of the code.
However, by manually tracing the recursive process I could finally understand that recursive functions do make sense.
I'll use my favorite example to explain it.
(My version of) Python Turtle code present in class:
import turtle
import copy
COLORS = ('red', 'green', 'blue', 'yellow', 'orange')
def tree_burst(level, base, turtle):
"""Draw a symmetrical ternary tree of height level with initial edges
of length base.
"""
if not level: # Pythonese for level == 0
#turtle.forward(base)
pass
else:
turtle_list = []
for h in range(5):
turtle_list.append(turtle.clone())
turtle_list[h].color(COLORS[h])
turtle_list[h].setheading(72 * h)
turtle_list[h].forward(base)
tree_burst(level - 1, base / 2, turtle_list[h])
if __name__ == '__main__':
T = turtle.Turtle()
T.color('red')
T.speed('slow')
# T.hideturtle()
tree_burst(3, 128, T)\
As mentioned in my previous blog, the resulting image is like:
When the main program is run, parameter "level" taken by the function is not 0 (yet). So it enters the 'else' part. While entering the for loop, a clone is created, a color is selected, and the direction is set. The turtle moves after all these preparations. After a line is drawn, the function prompts that it should repeat the calculation with (level - 1, base / 2, turtle_list[h]).
Then the function is run from the beginning, and the process is repeated until "level" reaches 0.
This period of recursion comes to an end. But wait, we haven't completed the for loop, yet. The program shouldn't stop. Since it has already taken 0 as the value of h, the function should then take 1 and repeat everything it has done.
What bothered me was that a recursive function seemed to be "called before completely defined". It was just a misunderstanding of the concept: the function is already well-defined when we run the program. It executes through the lines, knowing nothing about what is coming after the line currently being executed. Once it sees itself in its own body, it just go back to the first line with the new parameters given and continue executing, until it finds some way to escape, in this case, when level reaches 0. So an essential part for a recursive function, as far as I'm concerned, is the code which allows it to escape from the circle.
In this Python Turtle example, we actually see how a recursive function interacts with the for loop inside. I would say that a recursion and a loop are practically the same thing. They both deal with the same code executed over different parameters given each time. The only difference is that a loop is more explicit: we can easily find out when it will stop with (almost) no calculations. Recursion is thus just a fancier loop.

No comments:
Post a Comment