liveBook · Manning

Recursion

As explained in Grokking Simplicity

A programming technique in which a computation is defined in terms of one or more calls to the same computation.

Recursion defines a computation through calls to that same computation. It is especially useful for nested data, where the function’s structure can mirror the data’s structure while the call stack remembers where to continue. section 14.18 section 14.23

Make recursive functions safe by checking three conditions:

  • Write a base case that performs no recursive call and clearly stops the process. section 14.16
  • Provide a recursive case where the function calls itself. section 14.16
  • Move at least one argument closer to the base case on every call; repeating the same arguments creates an infinite loop. section 14.16

Array loops process elements in sequence, but nested operations get values while descending, modify the final value, and set copies while returning upward. Recursion and the call stack support this matching structure. Loops can be clearer in many cases; recursion becomes clearer when data is nested arbitrarily deeply. section 14.18 section 14.23

Updating a value through a nested path

A nestedUpdate() function stops when its key path is empty; otherwise, it removes the first key and recursively updates the remaining path. For example, incrementSizeByName(cart, name) can update [name, 'options', 'size'] by applying a size + 1 modification at the destination. section 14.18 section 14.16

function nestedUpdate(object, keys, modify) {
    if(keys.length === 0)
        return modify(object); #1 
    var key1 = keys[0];
    var restOfKeys = drop_first(keys);
    return update(object, key1, function(value1) {
        return nestedUpdate(value1, restOfKeys, modify);
    });
}

Inspect the nestedUpdate() implementation to see the empty-path base case, the shortened key path, and the recursive call inside update(). section 14.16

How Grokking Simplicity covers it

How deep it goes
Explains base cases, recursive cases, progress toward termination, call-stack behavior, and loops-versus-recursion tradeoffs.
Examples
Uses nestedUpdate() and incrementSizeByName() to modify values at known paths inside nested cart data.
What it assumes
Assumes familiarity with arrays and immutable data operations while teaching recursion safety from base cases onward.
What you can do after
Apply it via nestedUpdate() to modify values at known paths in deeply nested data.
How it connects
Connects recursion with nested data, call stacks, higher-order functions, immutable updates, loops, and abstraction barriers.

Also explained in

Compare how 23 books explain recursion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.