Recursive Calls and Ordinary Repeated Calls

Recursion happens when executing a function leads to another call to the same function, directly or through other calls.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Follow a nested computation
  2. Compare a caller-driven loop
  3. Distinguish separate tasks from unfinished dependent work
  4. Test the simplest case and a depth-sensitive case

Follow a nested computation

To add the numbers from three down to one, a recursive call at three can compute one term and wait for the result at two. Two waits for one. Each return supplies the pending addition, following ordinary call return behavior.

Compare a caller-driven loop

A loop can call an adding helper for 3, 2, and 1. Each call finishes before the next begins, so it keeps one active helper invocation. A loop accumulator can hold the intermediate sum at each step.[1][2]

Distinguish separate tasks from unfinished dependent work

Computing factorial for inputs two and four by making two separate top-level calls evaluates two tasks. Inside the second computation, factorial(4) awaits factorial(3) and ultimately needs its returned six to multiply by four. Each caller has work to resume. An ordinary loop over a list can issue several independent factorial calls, but it does not share their parameter frames. Trace the calls and returns separately when the same function name appears repeatedly. See tracing nested calls.

Test the simplest case and a depth-sensitive case

For nonnegative integers, recursion can stop at zero with the result one. A step that passes the original argument forever creates new frames without moving toward that case. Check an input of one to exercise both a recursive call and the stopping condition. A much larger input may exhaust the interpreter's stack even when the rule terminates mathematically. An accumulator in an iterative form can preserve the numerical result without the same call depth. See loop progress conditions.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Execution Model ↩