2title = "1.5.1 Walkthrough: Recursion"
6[Recursion](.) is a common pattern for solving certain problems in most programming
7languages, and Hoon is no exception. One of the classically recursive problems
8is that of factorial. The factorial of _n_ is the product of all positive
9integers less than or equal to N. Thus the factorial of 5, denoted as _5!_,
135 * 4 * 3 * 2 * 1 = 120
18Let's implement a factorial calculator in Hoon. To do so, we'll write a
19recursive `gate` (Hoon's equivalent of a function) to perform the relevant
20computation. Save the code below as `factorial.hoon` in your ship's `/gen`
30Our `gate` takes one sample (argument) `n` that must nest inside `@ud`, the
33Next we check to see if `n` is `1`. If so, the result is just `1`, since
36If, however, `n` is _not_ `1`, then we branch to the final line of the code,
37`(mul n $(n (dec n)))`, where the recursion logic lives. Here, we multiply `n`
38by the recursion of `n` minus `1`. `$` initiates recursion: it calls the gate
39that we're already in, but replaces its sample.
41In our example, we multiply `n` with the product of this _entire gate
42all over again_ with `$(n (dec n))`, except when that new gate has its sample
43decremented by one. This works recursively because each new gate will, of
44course, itself contain the code to call a further-decremented gate. Gates will
45continue to call new, further-decremented gates until `n` is `1`, and that `1`
46will be the final number to be multiplied by.
48Let's run the program in the Dojo:
55It may help to visualize the operation of our example gate. The pseudo-Hoon below
56illustrates what happens when we use it to find the factorial of 5:
61(mul 5 (mul 4 (factorial 3)))
62(mul 5 (mul 4 (mul 3 (factorial 2))))
63(mul 5 (mul 4 (mul 3 (mul 2 (factorial 1)))))
64(mul 5 (mul 4 (mul 3 (mul 2 1))))
65(mul 5 (mul 4 (mul 3 2)))
71It's easy to see how we're "floating" gate calls until we reach the final
72iteration of such calls that only produces a value. The `mul n` component of the
73gate leaves something like `mul 5`, waiting for the final series of terms
74to be operated upon. The `$(n (dec n))` component is what expands out the
75expression, as illustrated by `(factorial 4)`. Once the expression cannot be
76expanded out further, the operations work backwards, successively feeding values
77into the `mul` functions behind them.
79#### Tail-Call Optimization
81Our last example isn't a very efficient use computing resources. The
82pyramid-shaped illustration approximates what's happening on the **call stack**, a
83memory structure that tracks the instructions of the program. In our example
84code, every time a parent gate calls another gate, the gate being called is
85"pushed" to the top of the stack in the form of a frame. This process continues
86until a value is produced instead of a function, completing the stack.
97Once this stack of frames is completed, frames "pop" off the stack starting at
98the top. When a frame is popped, it executes the contained gate and passes
99produced data to the frame below it. This process continues until the stack
100is empty, giving us the gate's output.
102When a program's final expression uses the stack in this way, it's considered to
103be **not tail-recursive**. This usually happens when the last line of executable
104code calls more than one gate, our example code's `(mul n $(n (dec n)))` being
105such a case. That's because such an expression needs to hold each iteration of
106`$(n (dec n)` in memory so that it can know what to run against the `mul`
109To reiterate: if you have to manipulate the result of a recursion as the last
110expression of your gate, as we did in our example, the function is not
111tail-recursive, and therefore not very efficient with memory. A problem arises
112when we try to recurse more times that we have space on the stack. This will
113result in our computation failing and producing a stack overflow. If we tried
114to find the factorial of `5.000.000`, for example, we would almost certainly
115run out of stack space.
117But the Hoon compiler, like most compilers, is smart enough to notice when the
118last statement of a parent can reuse the same frame instead of needing to
119add new ones onto the stack. If we write our code properly, we can use a single
120frame that simply has its values replaced with each recursion.
122#### A Tail-Recursive Gate
124With a bit of refactoring, we can write a version of our factorial gate that
125_is_ tail-recursive and can take advantage of this feature:
133$(n (dec n), t (mul t n))
136The above code should look familiar. We are still building a gate that
137takes one argument `n`. This time, however, we are also putting a face on a
138`@ud` and setting it's initial value to 1. The `|-` here is used to create a new
139gate with one arm `$` and immediately call it. Think of `|-` as the recursion
142We then evaluate `n` to see if it is 1. If it is we return the value of `t`. In
143the case that `n` is anything other than 1, we perform our recursion:
146$(n (dec n), t (mul t n))
149All we are doing here is recursing our new gate and modifying the values of `n`
150and `t`. `t` is used as an accumulator variable that we use to keep a running
151total for the factorial computation.
153Let's use pseudo-Hoon to illustrate how the stack is working in this example for
166We simply multiply `t` and `n` to produce the new value of `t`, and then
167decrement `n` before repeating. Since this `$` call is the final and solitary
168thing that is run in the default case and since we are doing all computation
169before the call, this version is properly tail-recursive. We don't need to do
170anything to the result of the recursion except recurse it again. That means that
171each iteration can be replaced instead of held in memory.
175`$` (pronounced "buc") is, in its use with recursion, a reference to the gate that we are inside
176of. That's because a gate is just a core with a single arm named `$`. The
177subject is searched depth-first, head before tail, with faces skipped, and
178stopping on the first result. In other words, the first match found in the head
179will be returned. If you wished to refer to the outer `$` in this context, the
180idiomatic way would be to use [`^$`](@/docs/reference/hoon-expressions/rune/ket.md). The `^` operator
181skips the first match of a name.
1851. Write a recursive gate that produces the first _n_
186[Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number)
1882. Write a recursive gate that produces a list of moves to solve the
189[Tower of Hanoi problem](https://en.wikipedia.org/wiki/Tower_of_Hanoi).
190Disks are stacked on a pole by decreasing order of size. Move all of the
191disks from one pole to another with a third pole as a spare, moving one
192disc at a time, without putting a larger disk on top of a smaller disk.
194### [Next Up: Reading -- The Subject and its Legs](../the-subject-and-its-legs/)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list