I hadn't played with Marpa before so I thought I'd have a look:
#!/usr/bin/perl
use warnings;
use strict;
use Marpa::R2;
package Element;
sub newNode {
my ($value, $left, $right) = @_;
return bless {left => $left, right => $right, value => $value}, 'E
+lement';
}
sub doOp {
my @params = @_;
return newNode(@params[2, 1, 3],);
}
sub doConst {
my @params = @_;
return newNode($params[1]);
}
sub dump {
my ($node, $indent) = @_;
$indent //= '';
$node->{left}->dump("$indent ") if $node->{left};
print "$indent$node->{value}\n";
$node->{right}->dump("$indent ") if $node->{right};
}
package main;
my $syntax = <<'SYNTAX';
lexeme default = latm => 1
expression ::= expression '+' term action => doOp | term action => ::f
+irst
term ::= term '*' factor action => doOp | factor action => ::first
factor ::= constant action => doConst
constant ~ digits
digits ~ [\d]+
:discard ~ spaces
spaces ~ [\s]+
SYNTAX
my $grammar = Marpa::R2::Scanless::G->new({source => \$syntax});
my $input = '1 * 2 + 3 * 4';
my $root = $grammar->parse(\$input, 'Element');
($$root)->dump();
Prints:
1
*
2
+
3
*
4
No idea if that helps or not, but it was interesting to have a play.
Premature optimization is the root of all job security
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|