On this page
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:
- A base case that terminates without recursing.
- 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
- tuts/programming/foundations Linked here; links to this page; shared tags: #foundations, #prog, #programming
- tuts/programming/foundations/control_flow_and_composition Linked here; links to this page; shared tags: #foundations, #prog, #programming
- tuts/programming/paradigms/functional_programming Linked here; links to this page; shared tags: #prog, #programming
- tuts/programming/data_and_types Linked here; shared tags: #prog, #programming
- tuts/programming/memory_and_execution/call_stack_and_heap Linked here; shared tags: #prog, #programming
- tuts/programming/foundations/computational_thinking_and_abstraction shared tags: #foundations, #prog, #programming
- tuts/programming/foundations/state_variables_and_scope shared tags: #foundations, #prog, #programming
- tuts/programming shared tags: #prog, #programming
- tuts/programming/algorithms_and_dsa shared tags: #prog, #programming
- tuts/programming/algorithms_and_dsa/complexity_and_big_o shared tags: #prog, #programming