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