I am
choosing to revisit Week 5’s slog about Recursion because I think that I have a
lot to add to it. Recursion was one of the central themes of this course and
most of our assignments required recursive thinking to complete. I chose option
B for Assignment 3 because I wanted more practice writing recursion. When I
first learned about recursion it was hard to understand how the function calls
itself without breaking. I was confused because I kept thinking “If it calls
itself how can the function be complete?” and I didn’t find the answer to that
question until I sat down and traced a function that used recursion.
Recursion
works by having a case that is so simple that it can be solved without having
to call itself. This is essential, because if there is no base case, the
function will have an infinite loop and it will never stop calling itself. From
understanding this, it is helpful to realize that every time the function calls
itself, it is trying to get to the base case. If it doesn’t reach the base
case, it will never work. Tree structures are inherently recursive because as
the function traverses the nodes, it eventually reaches a leaf which is a
perfect base case.
Sometimes
in order to write a recursive function, the function needs more information
than what is being passed into it. This is when it is useful to create a helper
function has additional parameters so that it can do the bulk of the work and
update its local values in the main function as it “digs deeper” to get to the
base case.
Tracing recursion
is important because it helps us understand recursion without “looking under
the hood” at how the computer does it. Before I try writing recursion, I plan
pieces of my function by asking myself questions like “What is my base case?
How can I make the problem smaller? Do I need extra parameters? Do I need to
update values that I get from levels of recursion?” to create a blueprint of my
code. These questions help me understand what I want my function to return and how
I can accomplish what I want it to do. Planning ahead has helped make my code
look cleaner.
No comments:
Post a Comment