All episodes · From a List to Your Map App · Episode 4

Recursion: A Function That Calls Itself

Pressing play loads the video from YouTube.

How big is a folder that holds folders, that hold more folders? You could write steps for every level, or one short rule that keeps using itself.
We work out a folder's size with one recursive rule, find the base case that makes it stop, watch the call stack grow and shrink (and see what "stack overflow" really means), compare recursion with a loop, and grow a whole tree from a single rule.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

How big is this folder? It holds files, and other folders, which hold more files and more folders. You could write a long list of steps for every level. Or write one short rule that keeps using itself. Today: a function that calls itself. Recursion.

Here's the rule. The size of a folder is the size of its files, plus the size of each folder inside it. To use it on home, we need the size of photos. So we use the same rule on photos, and then on the folders inside photos. Each call hands the same question to a smaller folder, down and down, until a folder has no folders inside it. There, the answer is just its files. Then the answers travel back up. Each folder adds them together, until home has its total.

That bottom case, a folder with no folders inside, is called the base case. Every recursive function needs one. Without it, the function would call itself forever, like a folder that somehow holds itself.

How does the computer keep track of all these unfinished calls? With the stack from the last episode. Each call is pushed onto the call stack, holding its own folder and its own running total. When a call finishes, it pops off, and the one below picks up where it left off. If the calls go too deep, the stack runs out of room. That's the famous error: stack overflow.

Anything written with recursion can also be written with a loop, and a stack that you manage yourself. Pick whichever is clearer. For trees and anything nested, recursion usually wins.

Recursion: solve one small piece, and trust the same rule to handle the rest. Next time, the same idea finds anything in a sorted list in about twenty steps. Binary search. See you there.

Next episode: binary search, finding anything in a sorted list in about twenty steps.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal