home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!nestroy.wu-wien.ac.at!dec4.wu-wien.ac.at!neumann
- From: neumann@dec4.wu-wien.ac.at (Gustaf Neumann)
- Newsgroups: comp.lang.perl
- Subject: reduce fun
- Date: Tue, 22 Dec 92 14:17:54 MET
- Organization: WU-Wien
- Lines: 70
- Distribution: world
- Message-ID: <7250302748-326288@dec4.wu-wien.ac.at>
- NNTP-Posting-Host: dec4.wu-wien.ac.at
-
- here is a new version of reduce which allows left and right assiciative
- reduction. it allows for example to evaluate
-
- 9 op 5 op 3 op 1
-
- as yfx or as xfy
-
- op op
- op 1 9 op
- op 3 5 op
- 9 5 3 1
-
-
- where the y stands fo the nested term, and the f for the function.
- if op == '-', the yfx term is avaluated to 0, and the xfy term to 6.
-
-
- sub reduce_op {
- local($func,$op,@array) = @_;
- local($a,$b,$c);
-
- return @array[$[] if $#array == 0;
-
- if ($op eq 'yfx') {
- $a = shift @array;
- $b = &reduce_op($func,$op,@array);
- }
- elsif ($op eq 'xfy') {
- $b = pop @array;
- $a = &reduce_op($func,$op,@array);
- }
- elsif ($op eq 'xfyfx') {
- $c = pop @array;
- $a = shift @array;
- $b = &reduce_op($func,$op,@array);
- }
-
- return eval $func;
- }
-
- # here are some more obvious examples.
- # a and b are from left to right the operands in xfy or yfx
-
- print &reduce_op('$a > $b ? $a : $b','yfx',1,6,5,8,3,4),"\n";
- print &reduce_op('$a < $b ? $a : $b','yfx',1,6,5,8,3,4),"\n";
- print &reduce_op('$a + $b','yfx',1,6,5,8,3,4),"\n";
- print &reduce_op('$a - $b','xfy',9,5,3,1),"\n";
- print &reduce_op('$a - $b','yfx',9,5,3,1),"\n";
-
- #
- # the middle two are palindroms, the others remind me on towers of hanoi
-
- print &reduce_op('"$a $b $a"','xfy',1..5),"\n";
- print &reduce_op('"$a $b $a"','yfx',1..5),"\n";
- print &reduce_op('"$b $a $b"','xfy',1..5),"\n";
- print &reduce_op('"$b $a $b"','yfx',1..5),"\n";
-
- #
- # and finally ther Perl rap.
-
- print &reduce_op('"$c $b $b $a $a\n"','xfyfx',
- 'Hacker','Perl','other','an','just'),"\n";
-
- -gustaf
- --
- Gustaf Neumann neumann@dec4.wu-wien.ac.at, neumann@awiwuw11.bitnet
- Vienna University of Economics and Business Administration
- Augasse 2-6, A-1090 Vienna, Austria
- Tel: +43 (222) 31-336 x4533 Fax: 347-555
-
-