Give a little task a name
Picture
Imagine a small machine: give it 3, and it gives back 4. A function lets us name a task so we can use it again.
Predict
Our task adds one to its input. What does it give back for 8?
Let's look
- The task is the same; only the input changed.
A little Python, if you want it
def add_one(number):
return number + 1
assert add_one(3) == 4
assert add_one(8) == 9
The input goes into number. return sends the answer back to the caller. Calling a function doesn’t mean printing its answer.
Change one rule
A function needs another function’s answer. Can it wait for that answer, then continue?
Let's try it
Yes. The first function pauses at the call. When the helper returns, it continues from that point.
Connect
Stacks help us picture those paused calls. Recursion is when a function asks itself to handle a smaller case.