13 Recursion
Lesson goal Learn to write recursive functions with a base case and a recursive case, and understand why deep recursion in JS overflows the stack and how a trampoline avoids it.
Recursion is the ability of a function to call itself.
Recursion must meet two basic requirements in order to work correctly.
- The base case. This is the logic at which the recursion must stop — the base condition that stops the function from calling itself.
- The recursive case. This is the logic in which the function calls itself, usually with small changes to the arguments.
Recursion is frequently used in functional programming.
// our goal is to get the average age of the users
// ================================
// declarative style without recursion
// list of users
const fetchAllUsers = () => new Promise(resolve => resolve([
{ name: 'John', status: 'online', age: 28 },
{ name: 'Angel', status: 'online', age: 35 },
{ name: 'Michel', status: 'offline', age: 18 },
{ name: 'Anna', status: 'offline', age: 20 },
]))
// pipe from the "Function composition" lesson: passes each function's result to the next one
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x)
// getAgeAverage :: [a] -> Number
const getAgeAverage = (users) => pipe (
(users) => [
users.reduce ((init, { age }) => init + age, 0),
users.length
], // get the total age and the number of users
([allAges, quantity]) => Math.round (allAges / quantity), // compute the average age
console.log // log the result
) (users)
fetchAllUsers().then(getAgeAverage)
// ================================
// Recursive example
// ================================
// this recursive function is written with a tail call:
// the sum accumulates in the arguments, and in the base case the function
// returns the result right away, with no computation on the way back
// but we'll talk about that later
// now let's do the same thing with recursion
// recurAgeAverage :: ([a], Number, Number) -> Number
const recurAgeAverage = (
users, // array of user data
sumAges = 0, // sum of the users' ages
quantityUsers = users.length // initial number of users
) => {
// base case, the exit condition:
// the array is already empty
if (!users.length) {
// divide the sum of all ages by the number of users
// to get the average age of the users
return sumAges / quantityUsers
}
// recursive case: the function calls itself
// while the array still has elements
return recurAgeAverage (
users.slice(1), // the array without its first element
sumAges = sumAges + users[0]?.age, // add up each user's age
quantityUsers // pass along the previously saved number of users
)
}
// ================================
// Let's rewrite our function as a one-liner and call it
const recurAgeAverageF = (users, sumAges = 0, quantityUsers = users.length) =>
!users.length
? sumAges / quantityUsers
: recurAgeAverageF (
users.slice(1),
sumAges = sumAges + users[0]?.age,
quantityUsers
)
// the semicolon before the parenthesis is required: without it JS joins
// this parenthesis to the expression above and tries to call its result
;( async () => {
const users = await fetchAllUsers () // get the list of users
const averageAge = recurAgeAverageF (users) // get the average age recursively
console.log (averageAge) // log the result: 25.25
}
)()The example above with recursion may not be simple for some. So we will write a simpler example and visualize the calls. The main thing is, don't worry if something isn't clear right away.
// Our goal is to get the total rating of the users,
// that is, the sum of their ratings
const users = [
{ name: 'John', rating: 4.5 },
{ name: 'Angel', rating: 4 },
{ name: 'Michel', rating: 3 },
{ name: 'Anna', rating: 5 },
]
// sumRating :: [a] -> Number
const sumRating = (users) => {
// base case, the exit condition: the array is empty
if (!users.length) {
return 0
}
// recursive case:
// the rating of the first element is added
// to the call of the same function on the array without that element
return users[0].rating + sumRating (users.slice(1))
}
// let's shorten the syntax
const rateSum = (users) =>
!users.length
? 0
: users[0] + rateSum (users.slice(1))
// let's visualize the calls
// to keep it simple, use an array of numbers instead of the rating key
rateSum ([4.5, 4, 3, 5]) // returns 4.5 + rateSum ([4, 3, 5])
rateSum ([4, 3, 5]) // returns 4 + rateSum ([3, 5])
rateSum ([3, 5]) // returns 3 + rateSum ([5])
rateSum ([5]) // returns 5 + rateSum ([])
rateSum ([]) // returns 0: we reached the base case
// and here comes the key part: the calls on the stack return one by one
rateSum ([5]) // returns 5 + 0
rateSum ([3, 5]) // returns 3 + 5
rateSum ([4, 3, 5]) // returns 4 + 8
rateSum ([4.5, 4, 3, 5]) // returns 4.5 + 12
// final result: 16.5The "rateSum" function in the example above has one significant drawback: each call waits for the result of the next one so it can add its own number to it. So the depth of the call stack grows with the length of the array. Let's see what tail recursion changes here.
Why do we need this? Until a call finishes, its frame (arguments, local variables and the place to return the result to) stays on the call stack. The stack size is limited, so on a large array synchronous recursion fails with a stack overflow error (in Chrome and Node.js it is RangeError: Maximum call stack size exceeded).
// === Tail recursion optimization ====
// Let's rewrite the function so that the recursive call becomes a tail call
const rateSum = (users, result = 0) => {
// base case, the exit condition: the array is empty
// return the second argument, where we accumulate
// the results of all the calls
if (!users.length) {
return result
}
// recursive case, while the array has elements:
// on each call we add to the result in the second argument
// and keep calling, and in the base case we return the result
// the call is in tail position: after it the function has nothing left to do
return rateSum (users.slice(1), result = result + users[0])
}
// let's rewrite it all as a one-liner
const sum = (users, result = 0) => !users.length
? result
: sum (users.slice(1), result = result + users[0])
// let's visualize the calls
// to keep it simple, use an array of numbers instead of the rating key
sum ([4.5, 4, 3, 5], 0) // returns sum ([4, 3, 5], 0 + 4.5)
sum ([4, 3, 5], 4.5) // returns sum ([3, 5], 4.5 + 4)
sum ([3, 5], 8.5) // returns sum ([5], 8.5 + 3)
sum ([5], 11.5) // returns sum ([], 11.5 + 5)
sum ([], 16.5) // returns result 16.5
// the calls stop here: the result is already in the accumulator,
// and there is nothing left to compute on the way back
// there are as many calls as in rateSum without the accumulator: five
// with proper tail calls the engine keeps no frames of waiting calls,
// and the stack depth does not grow; but they only work in strict mode,
// and among browsers only Safari has them: V8 and SpiderMonkey don't
// this example is written without 'use strict', so its stack grows everywhere,
// even in Safari, just as it does without a tail callA tail call does not reduce the number of calls. It lets the engine drop the caller's stack frame: ES2015 requires this in strict mode (proper tail calls), and then the stack depth does not grow. Among browser engines, only JavaScriptCore (Safari) implements it; V8 (Chrome, Node.js) had it behind a flag and removed it, and SpiderMonkey (Firefox) does not have it. That is why deep recursion in JS needs a trampoline. In production code, don't rely on tail recursion unless you know exactly how many calls there will be.
Further on in the recursion section we will use techniques that let you safely use recursion in production code without counting the number of calls.
So how do we free up the call stack without overflowing it in production code?
- Make the code asynchronous, avoid blocking the thread, and free up the stack
- Use a trampoline. A thunk is a function with no arguments that defers a computation; a trampoline is a loop that keeps calling thunks while the result is a function. The recursive calls turn into a loop, so the stack does not grow.
// === 1. Asynchronous recursive call ====
// note that the recursive case is wrapped in a timer
// sumD :: ([Number], Number, (Number -> *)) -> Undefined
const sumD = (users, result = 0, callback) => {
// base case, the exit condition:
// once the array is empty, pass the result to the callback
if (!users.length) {
callback (result)
return
}
// the recursive case is called asynchronously,
// through a timer, so that the stack does not overflow
setTimeout (
() => sumD (users.slice(1), result = result + users[0], callback),
0
)
}
// let's shorten it
const sum = (users, result = 0, callback) =>
!users.length
? callback (result)
: setTimeout (
() => sum (users.slice(1), result = result + users[0], callback),
0
)
// let's try calling it
sum ([4.5, 4, 3, 5], 0, (total) => console.log(total)) // 16.5
// let's visualize the calls
sum ([4.5, 4, 3, 5], 0, (total) => console.log(total)) // schedules sum ([4, 3, 5], 0 + 4.5, callback) via a timer
// the call stack is free: microtasks (promises) and other macrotasks run between the steps
// the thread is not blocked
// the stack does not overflow
sum ([4, 3, 5], 4.5, (total) => console.log(total)) // schedules sum ([3, 5], 4.5 + 4, callback) via a timer
// the call stack is free: microtasks (promises) and other macrotasks run between the steps
// the thread is not blocked
// the stack does not overflow
sum ([3, 5], 8.5, (total) => console.log(total)) // schedules sum ([5], 8.5 + 3, callback) via a timer
// the call stack is free: microtasks (promises) and other macrotasks run between the steps
// the thread is not blocked
// the stack does not overflow
sum ([5], 11.5, (total) => console.log(total)) // schedules sum ([], 11.5 + 5, callback) via a timer
// the call stack is free: microtasks (promises) and other macrotasks run between the steps
// the thread is not blocked
// the stack does not overflow
sum ([], 16.5, (total) => console.log(total)) // calls callback with result
// Downsides of this approach
// Execution speed (performance) is low
// If you need long-running synchronous computations,
// it's better to move them to a web worker so they don't block the main thread;
// on a multi-core CPU the computation will also run in parallelLet's examine the logic of using a trampoline to avoid stack overflow. The trampoline works synchronously, unlike a call through a timer.
Let's look at the main principles of the trampoline.
- A trampoline is a wrapper function that gives our main function special behavior.
- The trampoline function returns another function that accepts arguments.
- Inside, it calls the main function once with these arguments.
- While the returned value is a function, the trampoline calls it in a loop. As soon as the result is not a function, the loop stops and the trampoline returns the result.
- In the base case the main function must return a result.
- In the recursive case the main function must return a function with no arguments (a thunk) that performs the next step.
// === Recursion via a trampoline ====
// note: the first call takes the function,
// and the second takes its arguments, which starts the computation
// trampoline :: ((...args -> *) -> (...args -> *))
const trampoline = (fn) => (...args) => {
// run the function with the given arguments
let result = fn(...args)
// keep looping while the function
// returns another function
while (typeof result == 'function') {
// store the result of the call in the variable
// and check what it returned
// result() *** remember this mark, we'll show later what this function is
result = result()
}
// as soon as the result of the call
// is not a function, return it
return result
}
// let's shorten the notation
// sumD :: ([Number], Number) -> (Number | (() -> *))
const sumD = (users, result = 0) => {
// if the array is empty, return the result
if (!users.length) {
return result
}
// note: here we must return a function with no arguments (a thunk)
// mark *** this is the function the trampoline calls inside the loop
return () => sumD (users.slice(1), result = result + users[0])
}
// let's rewrite the function as a one-liner
// sum :: ([Number], Number) -> (Number | (() -> *))
const sum = (users, result = 0) =>
!users.length
? result
: () => sum (users.slice(1), result = result + users[0])
// let's test the code
// pass our function through the trampoline
const sumTrampoline = trampoline (sum)
// now the functions will actually run in a loop
console.log (sumTrampoline ([4.5, 4, 3, 5], 0)) // 16.5// now let's visualize the calls
// the logic inside the trampoline for sumTrampoline ([4.5, 4, 3, 5], 0)
// === first call, before the loop =====
let result = sum ([4.5, 4, 3, 5], 0)
// puts () => sum ([4, 3, 5], 0 + 4.5) into result
// =======================
// === while loop: each iteration calls one function =====
result = result () // calls sum ([4, 3, 5], 4.5)
// puts () => sum ([3, 5], 4.5 + 4) into result
result = result () // calls sum ([3, 5], 8.5)
// puts () => sum ([5], 8.5 + 3) into result
result = result () // calls sum ([5], 11.5)
// puts () => sum ([], 11.5 + 5) into result
result = result () // calls sum ([], 16.5)
// puts 16.5 into result: it is no longer a function, so the loop ends
// =======================
// === leaving the trampoline =====
return result // 16.5
// =======================
// visualized as a diagram
// it's like a linked list of functions that isn't built in advance
// but grows as we go: the next element appears
// when the previous one is called
[
sum ([4.5, 4, 3, 5], 0), // first call: let result = fn(...args)
() => sum ([4, 3, 5], 4.5), // result = result() inside the loop
() => sum ([3, 5], 8.5), // result = result() inside the loop
() => sum ([5], 11.5), // result = result() inside the loop
() => sum ([], 16.5), // result = result() inside the loop
16.5 // the loop ends: return result
]Key points
- Recursion needs two cases: the base case stops the calls, and the recursive case calls the function again, usually with small changes to the arguments.
- Until a call finishes, its frame stays on the call stack. The stack size is limited, so on a large array synchronous recursion fails with a stack overflow.
- A tail call does not reduce the number of calls. ES2015 requires the engine to drop the caller's stack frame only in strict mode (proper tail calls), and among browser engines only JavaScriptCore (Safari) implements it. So production code should not rely on tail recursion unless you know exactly how many calls there will be.
- You can free the stack by running the recursive step asynchronously through a timer: the thread is not blocked, but such code is slow.
- A trampoline works synchronously: in the recursive case the function returns a thunk, a function with no arguments holding the next step, and the trampoline calls these functions in a loop while the result is a function. The stack does not grow.
Exercises
Exercise 1
Write a recursive function flatten that turns an array with nested arrays of any depth into a flat array, without using the built-in flat method. Define the base case first, then the recursive case: what to do when the first element is itself an array, and what to do when it is not.
Starter code
// flatten :: [*] -> [*]
const flatten = (arr) => {
// your code
}
console.log(flatten([1, [2, [3, [4]], 5], [[6]]]))
console.log(flatten([]))Expected output
[ 1, 2, 3, 4, 5, 6 ] []
Show solution
// flatten :: [*] -> [*]
const flatten = (arr) => {
// base case: an empty array has nothing to flatten
if (!arr.length) {
return []
}
const [head, ...tail] = arr
// recursive case: flatten a nested array with the same function,
// keep a plain value as is, and go on with the tail
return Array.isArray(head)
? [...flatten(head), ...flatten(tail)]
: [head, ...flatten(tail)]
}
console.log(flatten([1, [2, [3, [4]], 5], [[6]]]))
console.log(flatten([]))Exercise 2
The sumTo function adds up the numbers from 1 to n with plain recursion, and sumTo(100000) fails in Chrome and Node.js with RangeError: Maximum call stack size exceeded. Rewrite it for the trampoline from the lesson: keep the sum in an accumulator, and in the recursive case return a thunk with the next step. Check the result for 10 and for 100,000.
Starter code
// the trampoline from the lesson
// trampoline :: ((...args -> *) -> (...args -> *))
const trampoline = (fn) => (...args) => {
let result = fn(...args)
while (typeof result === 'function') {
result = result()
}
return result
}
// plain recursion: each call waits for the result of the next one
// sumTo :: Number -> Number
const sumTo = (n) => n === 0 ? 0 : n + sumTo(n - 1)
// sumToStep returns either the sum or a thunk with the next step
// sumToStep :: (Number, Number) -> (Number | (() -> *))
const sumToStep = (n, acc = 0) => {
// your code
}
// sumToSafe :: Number -> Number
const sumToSafe = trampoline(sumToStep)
console.log(sumToSafe(10))
console.log(sumToSafe(100000))Expected output
55 5000050000
Show solution
// the trampoline from the lesson
// trampoline :: ((...args -> *) -> (...args -> *))
const trampoline = (fn) => (...args) => {
let result = fn(...args)
while (typeof result === 'function') {
result = result()
}
return result
}
// sumToStep :: (Number, Number) -> (Number | (() -> *))
const sumToStep = (n, acc = 0) =>
n === 0
? acc // base case: the sum is already in the accumulator
: () => sumToStep(n - 1, acc + n) // recursive case: a thunk with the next step
// sumToSafe :: Number -> Number
const sumToSafe = trampoline(sumToStep)
console.log(sumToSafe(10))
console.log(sumToSafe(100000))Playground
Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.