Execute HQ9
1
class HQ9Interpreter {
2
has pointer;
3
has accumulator;
4
5
func bob (beer) {
6
func what { "#{beer ? beer : 'No more'} bottle#{beer-1 ? 's' : ''} of beer" }
7
func where { 'on the wall' }
8
func drink { beer--; "Take one down, pass it around," }
9
10
while (beer.is_pos) {
11
[[what(), where()], [what()],
12
[drink()], [what(), where()], []].each{.join(' ').say}
13
}
14
}
15
16
method run (code) {
17
var chars = code.chars;
18
accumulator = 0;
19
pointer = 0;
20
while (pointer < chars.len) {
21
given (chars[pointer].lc) {
22
when ('h') { say 'Hello world!' }
23
when ('q') { say code }
24
when ('9') { bob(99) }
25
when ('+') { accumulator++ }
26
default { warn %Q(Syntax error: Unknown command "#{chars[pointer]}") }
27
}
28
pointer++;
29
}
30
}
31
}
Copied!
Usage:
1
var hq9 = HQ9Interpreter();
2
hq9.run("hHq+++Qq");
Copied!

Output:

1
Hello world!
2
Hello world!
3
hHq+++Qq
4
hHq+++Qq
5
hHq+++Qq
Copied!
Or start a REPL (Read Execute Print Loop) and interact at the command line:
1
var hq9 = HQ9Interpreter();
2
loop {
3
var in = read('HQ9+>', String) \\ break;
4
hq9.run(in)
5
}
Copied!
Last modified 1yr ago
Copy link
Contents
Output: