In Monads in Perl, sleepingsquirrel gives an example of how to parse a prefix-notation equation using monads. After reading the article, I really couldn't see the point of monads (they seem just like functions with an implicit state). However, the prefix equations used in the article seemed like a perfect place to apply the sexeger technique.
As an added bonus, this version features per-operator callbacks.
use strict; use warnings 'all'; # to call: my %handlers = ( 'Div' => sub { $_[0] / $_[1] }, 'Mul' => sub { $_[0] * $_[1] }, 'Mod' => sub { $_[0] % $_[1] }, 'Exp' => sub { $_[0] ** $_[1] } ); print eval_prefix_equation("Mul Mod Exp Div Mul Div Div Con 18 Con 2 C +on 3 Con 4 Con 6 Con 2 Con 3 Con 4", \%handlers); # the method: sub eval_prefix_equation { my ($s,$h) = @_; my $r = reverse $s; # qr/Con (\d+(?:\.\d+)?/ backwards my $con = qr/(\d+(?:\.\d+)?) noC/; my $op = '(' . join('|', map { scalar reverse $_ } keys %$h) .')'; # just a sexeger; the while-loop condition resets our pos for us. $r =~ s/ $con \s+ $con \s+ $op / reverse('Con ' . $h->{reverse $3}( scalar(reverse $2), scalar(reverse $1) )); /ex while $r =~ /$op/; return scalar reverse $r; }
In reply to Parsing/Evaluating a prefix-notation equation using sexeger by jryan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |