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; }

Replies are listed 'Best First'.
Re: Parsing/Evaluating a prefix-notation equation using sexeger
by Roy Johnson (Monsignor) on Sep 01, 2004 at 17:01 UTC
    Why do you consider sexeger preferable to ordinary regexes for this?
    sub my_epe { my ($s,$h) = @_; my $op = '(' . join('|', keys %$h) . ')'; my $con = qr/Con (\d+(?:\.\d+)?)/; 1 while $s=~s/$op \s+ $con \s+ $con/'Con '.$h->{$1}($2,$3)/ex; $s; }

    Caution: Contents may have been coded under pressure.

      That's a really good point. :) I guess I saw that sexeger might be applicable, got excited, and just flew with it. A huge ++ for bringing me back down to earth.

Re: Parsing/Evaluating a prefix-notation equation using sexeger
by sleepingsquirrel (Chaplain) on Sep 17, 2004 at 22:04 UTC
    You inspired me to implement monadic parser combinators in perl. I will probably document the thing better, but here you go. Grab Monadic_parser and the corresponding needed module Do_notation.pm. For extra credit figure out a way to use perl's native regex engine instead of the roll-your-own kind used (i.e. /\d*/ instead of many(digits())). Maybe monads in perl aren't so useless after all.


    -- All code is 100% tested and functional unless otherwise noted.