[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Poor reverse polish calculator



On Mar 24, Alisdair McDiarmid said:

>I wanted to try to implement a reverse polish calculator in 80
>characters, but in the end I couldn't get it any smaller than 120:
>
>while(<>){for(split' '){if("+-*/"!~/([$_])/){push@k,$_;next;}
>($O,$Z)=splice@k,-2;push@k,eval"$O$1$Z";}print pop@k,"\n";}
>
>I know this code sucks and doesn't have any clever hacks in it, but
>can anyone write something functionally similar in eighty?

65 chars:

  while(<>){1 while s!(\S+)\s+(\S+)\s*([-+*/])!"$1 $3 $2"!ee;print}

It will break, however, on "2 3 +4 -", since it will be "54 -".  But that
should not occur, since tokens should be whitespace-separated.

Making it a 'perl -le', it comes in at

  1 while s!(\S+)\s+(\S+)\s*([-+*/])!"$1 $3 $2"!ee;print

which is 54.

-- 
Jeff "japhy" Pinyan      japhy@pobox.com      http://www.pobox.com/~japhy/
Are you a Monk?  http://www.perlmonks.com/     http://forums.perlguru.com/
Perl Programmer at RiskMetrics Group, Inc.     http://www.riskmetrics.com/
Acacia Fraternity, Rensselaer Chapter.         Brother #734


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe