Recursion – methods that call themselves
Open a Russian doll and there is a smaller doll inside, and inside that one a smaller one still – until the tiniest, which does not open. A method can work the same way: it solves a big problem by calling itself with a slightly smaller one, until the problem is so small that the answer is obvious. That is called recursion. A countdown:
def countdown(n)
if n == 0
puts "Chunky bacon!"
else
puts n
countdown(n - 1)
end
end
countdown(3)Every recursion has two parts. The base case (n == 0) is the tiniest doll: here the method stops calling itself. The recursive step does a little work and hands the rest, one size smaller, to the next call. Press ⏯ Step through on the cell above: countdown(3) calls countdown(2), which calls countdown(1) …
The classic example is the factorial: 5! = 5 · 4 · 3 · 2 · 1. Look at it differently and 5! is just 5 · 4!, and 4! is 4 · 3!, down to 1!, which is simply 1. That sentence is the method already:
def factorial(n)
return 1 if n <= 1
n * factorial(n - 1)
end
p factorial(5)
factorial(30)Ruby's integers grow as large as they need to, so factorial(30) has 33 digits without complaint. And without a base case? The method would call itself forever, every call waiting for the next one, until Ruby runs out of room for waiting calls and stops with SystemStackError: stack level too deep. You already know how to read such a message from lesson 28.
Recursion shines with things inside things – a box in a box in a box. This method adds up every number in an array, however deep it is nested:
def deep_sum(thing)
if thing.is_a?(Array)
thing.sum { |inner| deep_sum(inner) }
else
thing
end
end
boxes = [1, [2, 3], [[4], 5], [[[6]]]]
deep_sum(boxes)A loop would have to know how deep the boxes go. The recursion does not care: each call unpacks one layer and leaves the rest to the next call. Folders in folders, the tags of an HTML page (lesson 52), a family tree – all of them are things inside things.
Recursion can also be wastefully slow. In the Fibonacci numbers – 0, 1, 1, 2, 3, 5, 8 … – each one is the sum of the two before it. Written as a recursion that is two lines, but fib(30) would call itself 2.7 million times, because it works out the same numbers over and over. A hash as a memory fixes it: what has been computed once is looked up (||= only computes when the hash has nothing yet):
def fib(n)
return n if n < 2
fib(n - 1) + fib(n - 2)
end
def fast_fib(n, memo = {})
return n if n < 2
memo[n] ||= fast_fib(n - 1, memo) + fast_fib(n - 2, memo)
end
p fib(15)
fast_fib(90)fast_fib(90) makes fewer than 200 calls; the plain fib(90) would still be running when the sun burns out.
Finally, a puzzle that is hard to solve with loops and short with recursion: the Towers of Hanoi. Discs of different sizes sit on the left peg, the largest at the bottom. Move them all to the right peg – one disc at a time, and never a larger disc on a smaller one. The trick: to move n discs, move the n - 1 above it to the spare peg, then the big one, then the n - 1 back on top:
def hanoi(n, from, to, spare)
return if n == 0
hanoi(n - 1, from, spare, to)
puts "Disc #{n}: #{from} -> #{to}"
hanoi(n - 1, spare, to, from)
end
hanoi(3, "left", "right", "middle")Seven moves for three discs, 2n - 1 in general. A legend tells of monks who move 64 golden discs; at one move per second they need 585 billion years. Try hanoi(4, …) – or step through hanoi(2, …) with ⏯ and watch the calls pile up and unwind. In lesson 33 Chunky draws with recursion: a snowflake whose edges are snowflakes.
power(base, exponent): power(2, 10) is 2 · 2 · … · 2, ten times, so 1024. Base case: anything to the power of 0 is 1. Recursive step: base times power(base, exponent - 1). Without **, of course!# def power(base, exponent)
# return ... if exponent == 0 # the base case: anything to the power of 0 is 1
# ... # the step: base times power(base, exponent - 1)
# end
# power(2, 10)
unbox(thing), which unpacks any nesting into one flat list: unbox([1, [2, [3, [4]]], 5]) gives [1, 2, 3, 4, 5], and a single thing gives a list with just that thing, unbox(7) → [7]. Without flatten – that's the point!# def unbox(thing)
# ... # an Array: unbox every element and join the results
# ... # anything else: a list with just that thing
# end
# unbox([1, [2, [3, [4]]], 5])