on master help sign in
added fibonacci workbook example
02dd8b1David Kerschner
learn/hoon/workbook/fib.mdnew file+53
@@ -0,0 +1,53 @@
1+Write a generator that produce a list of Fibonacci numbers up to n.
2+
3+```
4+|= n=@ud
5+%- flop
6+=+ [i=0 p=0 q=1 r=*(list @ud)]
7+|- ^+ r
8+?: =(i n) r
9+%= $
10+ i +(i)
11+ p q
12+ q (add p q)
13+ r [q r]
14+==
15+```
16+
17+First we need to produce a gate which takes an `@ud` so we know when to stop producing the list.
18+
19+```
20+%- flop
21+```
22+Next we're going to call `flop` on the output of the rest of the program. `flop` is a standard library function to reverse a list. Why are we using this instead of producing the list in the order we want it in the first place? With lists adding an element to the end is an expensive operation that gets more expensive the longer the list is. Adding an element to the front however is cheap. In Big O Notation, adding to the end of a list is O(n) and the front is O(1).
23+
24+```
25+=+ [i=0 p=0 q=1 r=*(list @ud)]
26+```
27+
28+We are going to need several values throughout the execution of this task so we set them all up here. It's worth noticing that because the subject is searched head first, ignoring faces, we can define a number of faces at once by putting them in a tuple like this.
29+
30+The only one of these that is interesting is `r` We're using `*` to bunt, or get the default value for, the mold `(list @ud)`.
31+
32+```
33+|- ^+ r
34+```
35+
36+Next we define the trap that will contain the majority of our program. We also use `^+` to cast the output by example. This will result in the output being the same type as `r`, a list of `@ud`.
37+
38+```
39+?: =(i n) r
40+```
41+
42+Here is our terminating case, if `i` and `n` are equal we produce `r` as the result.
43+
44+```
45+%= $
46+ i +(i)
47+ p q
48+ q (add p q)
49+ r [q r]
50+==
51+```
52+
53+The final expression in our program calls the `$` arm of the trap we are in with some changes. We increment `i`, set `p` to be `q` and `q` becomes the sum of `q` and `q`. `r` becomes a cell of `q` and whatever `r` was previously. This is the list that will get flopped to produce the result at the end of the computation.