On this page
  1. Functions & Recursion
  2. Contents
  3. Call Frames & Abstraction
  4. Recursion, Base Cases & Stack Depth
  5. Higher-Order Functions

Functions & Recursion

Prev: Control Flow & Composition | Up: foundations | Next: data_and_types
Rel: Call Stack & Heap, Functional Programming
Ref: Wikipedia — Recursion (Computer Science)
Tags: #public #prog #programming #foundations #functions


Contents


Call Frames & Abstraction

Calling a function pushes a stack frame holding its parameters, local variables, and return address. When the function returns, its frame pops off the call stack.


Recursion, Base Cases & Stack Depth

Every valid recursive function requires:

  1. A base case that terminates without recursing.
  2. A recursive step that strictly reduces the problem toward the base case.
function factorial(n):
  if n <= 1: return 1          // base case
  return n * factorial(n - 1)  // recursive step

Recursion shines on naturally recursive structures (trees, ASTs, divide-and-conquer). Unless a language guarantees Tail Call Optimization (TCO), deep recursion risks a stack overflow and should be converted to an explicit loop or stack.


Higher-Order Functions

A higher-order function accepts functions as arguments or returns a function as its result — enabling reusable abstractions like map, filter, sort(key=...), and decorators.

Linked from

Related notes