root/examples/hq9+.pl

Revision 14929, 1.6 kB (checked in by wolverian, 2 years ago)

r32@pupu: wolverian | 2006-12-19 19:24:00 +0200
update the hq9+ example

  • Property svn:mime-type set to text/plain; charset=UTF-8
  • Property svn:eol-style set to native
Line 
1class HQ9Plus;
2
3# 2006-12-19 (rough) update to current spec
4
5my subset HQ9PlusProgram
6    of Str
7    where /^ <[hq9+]>* $/;
8
9my subset HQ9PlusStep
10    of HQ9PlusProgram
11    where { .chars == 1 };
12
13has HQ9PlusProgram $.program;
14has Int            $.accumulator = 0;
15has Int            $position = 0; # twigilless are private
16
17has %actions = (
18    'h' => { self.hello },
19    'q' => { self.quine },
20    '9' => { self.nine  },
21    '+' => { self.plus  },
22);
23
24method run () {
25    # Java, anyone? Feel free to fix this.
26    loop {
27        .step;
28        CATCH {
29            when Error::OutOfBounds {
30                return; # end of program
31            }
32            default { fail }
33        }
34    }
35}
36
37method step () {
38    given $.program.substr($position++, 1) {
39        $actions<$_>();
40    }
41}
42
43my method hello () { say "Hello, world!" }
44my method quine () { say $.program }
45my method plus  () { $.accumulator++ }
46my method nine  () {
47    my Int $i = 99;
48
49    while $i {
50        say qq:to/END/;
51            $i bottles of beer on the wall
52            $i bottles of beer!
53            Take one down, pass it around
54            END
55        $i--;
56        say "$i bottles of beer on the wall!"
57    }
58}
59
60=head1 NAME
61
62HQ9Plus - A HQ9+ implementation
63
64=head1 SYNOPSIS
65
66    HQ9Plus.new(program => $foo).run;
67
68    my $program = HQ9Plus.new(program => $foo);
69
70    while ... {
71        $program.step;
72        ...inspect the program state...
73    }
74
75=head1 DESCRIPTION
76
77C<HQ9Plus> implements a I<HQ9+> interpreter with stepping.
78
79=head1 SEE ALSO
80
81http://en.wikipedia.org/wiki/HQ9+
82
83=head1 AUTHOR
84
85Ilmari Vacklin <ilmari.vacklin@helsinki.fi>
86
87=head1 LICENSE
88
89Public domain.
Note: See TracBrowser for help on using the browser.