on master help sign in
Re-added even.md
commitc3508c0cafd707a92abc53dd013e3f20d0498a6f authorDavid Kerschner <dkerschner@hcoop.net> dateMon 20 May 2019, 14:20 (7 years ago) parentfcab297
1 file changed+54
learn/hoon/workbook/even.md+54
learn/hoon/workbook/even.mdnew file+54
@@ -0,0 +1,54 @@
1+Write a generator that takes an integer and checks if it even and between 1 and 100.
2+
3+```
4+:- %say
5+|= [* [n=@ud ~] ~]
6+:- %noun
7+?: ?& =(0 (mod n 2))
8+ ?& (gte n 1)
9+ ?! (gth n 100)
10+ ==
11+ ==
12+ %.y
13+%.n
14+```
15+
16+On the very first line, with `:- %say` we are beginning to create a generator of the `%say` kind. The result of a `%say` generator is a cell with a head of `%say` and tail that is a gate, itself producing a `cask`, a pair of a `mark` and some data. For more information about `%say` generators, see the [Generators](/using/generators) documentation.
17+
18+```
19+|= [* [n=@ud ~] ~]
20+```
21+
22+The code above builds a gate. The gate's first argument is a cell provided by Dojo that contains some system information we're not going to use, so we use `*` to indicate "any noun." The next cell is our arguments provided to the generator upon invocation at the `dojo`. Here we only want one `@ud` with the face `n`.
23+
24+```
25+:- %noun
26+```
27+
28+This code is the third line of the `%say` "boilerplate, and it produces a `cask` with the head of `%noun`. We could use any `mark` here, but `%noun` is the most generic type, able to fit any data.
29+
30+Below we'll examine the the series of `?` runes used.
31+
32+```
33+?: ?& =(0 (mod n 2))
34+```
35+
36+`?:` is the simplest "wut" rune. It takes three expressions: a boolean test, a yes-branch, and a no-branch. The yes-branch is executed when the test evaluates to `%.y` and the no-branch is executed when the test evaluates to `%.n`. Here the yes-branch is `%.y` and the no-branch is `%.n`. The boolean test is the more complicated portion. First we're going to use `?&` to combine to expressions with a logical and operation.
37+
38+The first expression is:
39+
40+```
41+=(0 (mod n 2))
42+```
43+
44+which simply asks if n is even or not.
45+
46+The second expression is:
47+
48+```
49+ ?& (gte n 1)
50+ ?! (gth n 100)
51+ ==
52+```
53+
54+Again we and two expressions with `?&` the first is just checking if n is greater than or equal to 1. The second we have artificially use the `?!` rune to demonstrate its use. `?!` is a logical NOT operation. We use that on the result of asking if n is greater than 100 to effectively ask if it is less than or equal to 100.