Codacoda
Back to Academy

functional programming

Recursion in FP

In functional programming, recursion replaces imperative loops as the primary mechanism for iteration. A recursive function calls itself with a progressively simpler version of the problem until it reaches a base case. Think of Russian nesting dolls: you open each one to find a smaller one inside until you reach the smallest. Tail-call optimization (TCO) allows properly written recursive functions to run in constant stack space, making them as efficient as loops.

Use Cases

  • Traversing nested data structures like file trees, JSON configs, or DOM nodes
  • Implementing divide-and-conquer algorithms (merge sort, quicksort, binary search)
  • Flattening arbitrarily nested arrays or objects of unknown depth
  • Processing recursive data formats like org charts, category trees, or comment threads

Implementation

Output

Click "Run Code" to see output...