on 01ac191 help sign in
62 lines 2.0 kB history raw
1---
2sort: 1
3next: true
4title: Demo
5---
7# Demo
9Here's everyone's favorite whiteboard example, FizzBuzz. Each
10line is commented with its number:
12```
13:gate end/atom :: 1
14:var count 1 :: 2
15:loop :: 3
16:cast (list tape) :: 4
17:if =(end count) :: 5
18 ~ :: 6
19:cons :: 7
20 :if =(0 (mod count 15)) :: 8
21 "FizzBuzz" :: 9
22 :if =(0 (mod count 5)) :: 10
23 "Fizz" :: 11
24 :if =(0 (mod count 3)) :: 12
25 "Buzz" :: 13
26 (text :wrap(count)) :: 14
27:moar(count (add 1 count)) :: 15
28```
30Can you understand this code by just looking at it? Maybe.
31But let's explain it anyway.
33Hoon is a functional language. FizzBuzz is usually defined as a
34side effect, but Hoon has no side effects. This code will
35*make* a list of strings, not *print* a list of strings.
37Line 1 defines a function of one argument, `end`, an unsigned
38integer.
40Line 2 declares a variable, `count`, with initial value `1`.
42Line 3 begins a loop.
44Line 4 casts the product of the loop to a list of `tape`
45(string as a character list).
47Line 5 checks if `count` equals `end`. If so, line 6 (and the
48whole loop) produces the value `~`, null, the empty list. If
49not, line 7 begins an ordered pair.
51The head of the pair is "FizzBuzz", or "Fizz", or "Buzz", if the
52respective tests hit. If not, line 14 wraps a runtime type
53around `count`, then prints the type-value pair to a string (like
54C `sprintf()`). This string is the first item in the output list.
56The tail of the pair is line 15, which repeats the loop (like
57Clojure `recur`), with `count` incremented. This list of strings
58is the rest of the output list.
60You can test this code by mounting your home desk with `|mount %home`;
61copying it into `home/gen/fizzbuzz.hoon` in your Urbit pier; then
62typing `+fizzbuzz 100` in the Urbit dojo (shell).