<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">

## Last modification: 8/3/00 by akp
## Originally written by Daniel Martin, Dept of Math, John Hopkins
## Additions and modifications were made by James Martino, Dept of Math, John Hopkins
## Additions and modifications were made by Arnold Pizer, Dept of Math, Univ of Rochester

#use Data::Dumper;

package AlgParser;
use HTML::Entities;

%close = ();

sub new {
  my $package = shift;
  my (%ret);
  $ret{string} = "";
  $ret{posarray} = [];
  $ret{parseerror} = "";
  $ret{parseresult} = [];
  bless \%ret, $package;
  return \%ret;
}

sub inittokenizer {
  my($self, $string) = @_;
  $self-&gt;{string} =~ m/\G.*$/g;
  $self-&gt;{string} = undef;
  $self-&gt;{string} = $string;
  $self-&gt;{string} =~ m/\G.*$/g;
  $self-&gt;{string} =~ m/^/g;
}

$close{'{'} = '}';
$close{'['} = ']';
$close{'('} = ')';

$binoper3 = '(?:\\^|\\*\\*)';
$binoper2 = '[/*_,]';
$binoper1 = '[-+=&gt;&lt;%!#]';
$openparen = '[{(\\[]';
$closeparen = '[})\\]]';
$varname = '[A-Za-z](?:_[0-9]+)?';
$specialvalue = '(?:e|pi|da|db|dc|de|df|dg|dh|di|dj|dk|dl|dm|dn|do|dp|dq|dr|ds|dt|du|dv|dw|dx|dy|dz|infty|alpha|bita|gamma|zita|thita|iota|kappa|lambda|mu|nu|xi|rho|sigma|tau|phi|chi|psi|omega|zepslon|zdelta|xeta|zupslon|zeroplace)';
$numberplain = '(?:\d+(?:\.\d*)?|\.\d+)';
$numberE = '(?:' . $numberplain . 'E[-+]?\d+)';
$number = '(?:' . $numberE . '|' . $numberplain . ')';
#
#  DPVC -- 2003/03/31
#       added missing trig and inverse functions
#
#$trigfname = '(?:cosh|sinh|tanh|cot|(?:a(?:rc)?)?cos|(?:a(?:rc)?)?sin|' .
#    '(?:a(?:rc)?)?tan|sech?)';
$trigfname = '(?:(?:a(?:rc)?)?(?:sin|cos|tan|sec|csc|cot)h?)';
#
#  End DPVC
#
$otherfunc = '(?:exp|abs|logten|log|ln|sqrt|sgn|step|fact|int|lim|fun[a-zA-Z])';
$funcname = '(?:' . $otherfunc . '|' . $trigfname . ')';

$tokenregexp = "(?:($binoper3)|($binoper2)|($binoper1)|($openparen)|" .
    "($closeparen)|($funcname)|($specialvalue)|($varname)|" .
    "($numberE)|($number))";

sub nexttoken {
  my($self) = shift;
  $self-&gt;{string} =~ m/\G\s+/gc;
  my($p1) = pos($self-&gt;{string}) || 0;
  if(scalar($self-&gt;{string} =~ m/\G$tokenregexp/gc)) {
        push @{$self-&gt;{posarray}}, [$p1, pos($self-&gt;{string})];
        if (defined($1)) {return ['binop3',  $1];}
        if (defined($2)) {return ['binop2',  $2];}
        if (defined($3)) {return ['binop1',  $3];}
        if (defined($4)) {return ['openp',   $4];}
        if (defined($5)) {return ['closep',  $5];}
        if (defined($6)) {return ['func1',   $6];}
        if (defined($7)) {return ['special', $7];}
        if (defined($8)) {return ['varname', $8];}
        if (defined($9)) {return ['numberE', $9];}
        if (defined($10)) {return ['number', $10];}
  }
  else {
    push @{$self-&gt;{posarray}}, [$p1, undef];
    return undef;
  }
}

sub parse {
  my $self = shift;
  $self-&gt;{parseerror} = "";
  $self-&gt;{posarray} = [];
  $self-&gt;{parseresult} = ['top', undef];
  my (@backtrace) = (\$self-&gt;{parseresult});
  my (@pushback) = ();

  my $currentref = \$self-&gt;{parseresult}-&gt;[1];
  my $curenttok;

  my $sstring = shift;
  $self-&gt;inittokenizer($sstring);
  $currenttok = $self-&gt;nexttoken;
  if (!$currenttok) {
    if ($self-&gt;{string} =~ m/\G$/g) {
      return $self-&gt;error("empty");
    } else {
      my($mark) = pop @{$self-&gt;{posarray}};
      my $position = 1+$mark-&gt;[0];
      return $self-&gt;error("Illegal character at position $position", $mark);
    }
  }
  # so I can assume we got a token
  local $_;
  while ($currenttok) {
    $_ = $currenttok-&gt;[0];
    /binop1/ &amp;&amp; do {
      # check if we have a binary or unary operation here.
      if (defined(${$currentref})) {
        # binary - walk up the tree until we hit an open paren or the top
        while (${$currentref}-&gt;[0] !~ /^(openp|top)/) {
          $currentref = pop @backtrace;
        }
        my $index = ((${$currentref}-&gt;[0] eq 'top')?1:3);
        ${$currentref}-&gt;[$index] = ['binop1', $currenttok-&gt;[1],
                                    ${$currentref}-&gt;[$index], undef];
        push @backtrace, $currentref;
        push @backtrace, \${$currentref}-&gt;[$index];
        $currentref = \${$currentref}-&gt;[$index]-&gt;[3];
      } else {
        # unary
        ${$currentref} = ['unop1', $currenttok-&gt;[1], undef];
        push @backtrace, $currentref;
        $currentref = \${$currentref}-&gt;[2];
      }
    };
    /binop2/ &amp;&amp; do {
      if (defined(${$currentref})) {
        # walk up the tree until an open paren, the top, binop1 or unop1
        # I decide arbitrarily that -3*4 should be parsed as -(3*4)
        # instead of as (-3)*4.  Not that it makes a difference.

        while (${$currentref}-&gt;[0] !~ /^(openp|top|binop1)/) {
          $currentref = pop @backtrace;
        }
        my $a = ${$currentref}-&gt;[0];
        my $index = (($a eq 'top')?1:3);
        ${$currentref}-&gt;[$index] = ['binop2', $currenttok-&gt;[1],
                                    ${$currentref}-&gt;[$index], undef];
        push @backtrace, $currentref;
        push @backtrace, \${$currentref}-&gt;[$index];
        $currentref = \${$currentref}-&gt;[$index]-&gt;[3];
      } else {
        # Error
        my($mark) = pop @{$self-&gt;{posarray}};
        my $position =1+$mark-&gt;[0];
        return $self-&gt;error("Didn't expect " . $currenttok-&gt;[1] .
                            " at position $position" , $mark);
      }
    };
    /binop3/ &amp;&amp; do {
      if (defined(${$currentref})) {
        # walk up the tree until we need to stop
        # Note that the right-associated nature of ^ means we need to
        # stop walking backwards when we hit a ^ as well.
        while (${$currentref}-&gt;[0] !~ /^(openp|top|binop[123]|unop1)/) {
          $currentref = pop @backtrace;
        }
        my $a = ${$currentref}-&gt;[0];
        my $index = ($a eq 'top')?1:($a eq 'unop1')?2:3;
        ${$currentref}-&gt;[$index] = ['binop3', $currenttok-&gt;[1],
                                    ${$currentref}-&gt;[$index], undef];
        push @backtrace, $currentref;
        push @backtrace, \${$currentref}-&gt;[$index];
        $currentref = \${$currentref}-&gt;[$index]-&gt;[3];
      } else {
        # Error
        my($mark) = pop @{$self-&gt;{posarray}};
        my $position = 1+$mark-&gt;[0];
        return $self-&gt;error("Didn't expect " . $currenttok-&gt;[1] .
                            " at position $position", $mark);
      }
    };
    /openp/ &amp;&amp; do {
      if (defined(${$currentref})) {
        # we weren't expecting this - must be implicit
        # multiplication.
        push @pushback, $currenttok;
        $currenttok = ['binop2', 'implicit'];
        next;
      } else {
        my($me) = pop @{$self-&gt;{posarray}};
        ${$currentref} = [$currenttok-&gt;[0], $currenttok-&gt;[1], $me, undef];
        push @backtrace, $currentref;
        $currentref = \${$currentref}-&gt;[3];
      }
    };
    /func1/ &amp;&amp; do {
      if (defined(${$currentref})) {
        # we weren't expecting this - must be implicit
        # multiplication.
        push @pushback, $currenttok;
        $currenttok = ['binop2', 'implicit'];
        next;
      } else {
        # just like a unary operator
        ${$currentref} = [$currenttok-&gt;[0], $currenttok-&gt;[1], undef];
        push @backtrace, $currentref;
        $currentref = \${$currentref}-&gt;[2];
      }
    };
    /closep/ &amp;&amp; do {
      if (defined(${$currentref})) {
        # walk up the tree until we need to stop
        while (${$currentref}-&gt;[0] !~ /^(openp|top)/) {
          $currentref = pop @backtrace;
        }
        my $a = ${$currentref}-&gt;[0];
        if ($a eq 'top') {
          my($mark) = pop @{$self-&gt;{posarray}};
          my $position = 1+$mark-&gt;[0];
          return $self-&gt;error("Unmatched close " . $currenttok-&gt;[1] .
                              " at position $position", $mark);
        } elsif ($close{${$currentref}-&gt;[1]} ne $currenttok-&gt;[1]) {
          my($mark) = pop @{$self-&gt;{posarray}};
          my $position = 1+$mark-&gt;[0];
          return $self-&gt;error("Mismatched parens at position $position"
                              , ${$currentref}-&gt;[2], $mark);
        } else {
          ${$currentref}-&gt;[0] = 'closep';
          ${$currentref}-&gt;[2] = pop @{${$currentref}};
        }
      } else {
        # Error - something like (3+4*)
        my($mark) = pop @{$self-&gt;{posarray}};
        my $position = 1+$mark-&gt;[0];
        return $self-&gt;error("Premature close " . $currenttok-&gt;[1] .
                            " at position $position", $mark);
      }
    };
    /special|varname|numberE?/ &amp;&amp; do {
      if (defined(${$currentref})) {
        # we weren't expecting this - must be implicit
        # multiplication.
        push @pushback, $currenttok;
        $currenttok = ['binop2', 'implicit'];
        next;
      } else {
        ${$currentref} = [$currenttok-&gt;[0], $currenttok-&gt;[1]];
      }
    };
    if (@pushback) {
      $currenttok = pop @pushback;
    } else {
      $currenttok = $self-&gt;nexttoken;
    }
  }
  # ok, we stopped parsing.  Now we need to see why.
  if ($self-&gt;{parseresult}-&gt;[0] eq 'top') {
    $self-&gt;{parseresult} = $self-&gt;arraytoexpr($self-&gt;{parseresult}-&gt;[1]);
  } else {
    return $self-&gt;error("Internal consistency error; not at top when done");
  }
  if ($self-&gt;{string} =~ m/\G\s*$/g) {
    if (!defined(${$currentref})) {
      $self-&gt;{string} .= " ";
      return $self-&gt;error("I was expecting more at the end of the line",
                        [length($self-&gt;{string})-1, length($self-&gt;{string})]);
    } else {
      # check that all the parens were closed
      while (@backtrace) {
        $currentref = pop @backtrace;
        if (${$currentref}-&gt;[0] eq 'openp') {
          my($mark) = ${$currentref}-&gt;[2];
          my $position = 1+$mark-&gt;[0];
          return $self-&gt;error("Unclosed parentheses beginning at position $position"
                         , $mark);
        }
      }
      # Ok, we must really have parsed something
      return $self-&gt;{parseresult};
    }
  } else {
      my($mark) = pop @{$self-&gt;{posarray}};
      my $position = 1+$mark-&gt;[0];
      return $self-&gt;error("Illegal character at position $position",$mark);
  }
}

sub arraytoexpr {
  my ($self) = shift;
  return Expr-&gt;fromarray(@_);
}

sub error {
  my($self, $errstr, @markers) = @_;
#  print STDERR Data::Dumper-&gt;Dump([\@markers],
#                                  ['$markers']);
  $self-&gt;{parseerror} = $errstr;
  my($htmledstring) = '&lt;tt class="parseinput"&gt;';
  my($str) = $self-&gt;{string};
#  print STDERR Data::Dumper-&gt;Dump([$str], ['$str']);
  my($lastpos) = 0;
  $str =~ s/ /\240/g;
  while(@markers) {
    my($ref) = shift @markers;
    my($pos1) = $ref-&gt;[0];
    my($pos2) = $ref-&gt;[1];
    if (!defined($pos2)) {$pos2 = $pos1+1;}
    $htmledstring .= encode_entities(substr($str,$lastpos,$pos1-$lastpos)) .
           '&lt;b class="parsehilight"&gt;' .
           encode_entities(substr($str,$pos1,$pos2-$pos1)) .
           '&lt;/b&gt;';
    $lastpos = $pos2;
  }
#  print STDERR Data::Dumper-&gt;Dump([$str, $htmledstring, $lastpos],
#                                  ['$str', '$htmledstring', '$lastpos']);
  $htmledstring .= encode_entities(substr($str,$lastpos));
  $htmledstring .= '&lt;/tt&gt;';
#  $self-&gt;{htmlerror} = '&lt;p class="parseerr"&gt;' . "\n" .
#                       '&lt;span class="parsedesc"&gt;' .
#                       encode_entities($errstr) . '&lt;/span&gt;&lt;br&gt;' . "\n" .
#                       $htmledstring . "\n" . '&lt;/p&gt;' . "\n";
  $self-&gt;{htmlerror} =  $htmledstring ;
  $self-&gt;{htmlerror} =  'empty' if $errstr eq 'empty';
  $self-&gt;{error_msg} = $errstr;

#  warn $errstr . "\n";
  return undef;
}

sub tostring {
  my ($self) = shift;
  return $self-&gt;{parseresult}-&gt;tostring(@_);
}

sub tolatex {
  my ($self) = shift;
  return $self-&gt;{parseresult}-&gt;tolatex(@_);
}

sub tolatexstring { return tolatex(@_);}

sub exprtolatexstr {
  return exprtolatex(@_);
}

sub exprtolatex {
  my($expr) = shift;
  my($exprobj);
  if ((ref $expr) eq 'ARRAY') {
    $exprobj = Expr-&gt;new(@$expr);
  } else {
    $exprobj = $expr;
  }
  return $exprobj-&gt;tolatex();
}

sub exprtostr {
  my($expr) = shift;
  my($exprobj);
  if ((ref $expr) eq 'ARRAY') {
    $exprobj = Expr-&gt;new(@$expr);
  } else {
    $exprobj = $expr;
  }
  return $exprobj-&gt;tostring();
}

sub normalize {
  my ($self, $degree) = @_;
  $self-&gt;{parseresult} = $self-&gt;{parseresult}-&gt;normalize($degree);
}

sub normalize_expr {
  my($expr, $degree) = @_;
  my($exprobj);
  if ((ref $expr) eq 'ARRAY') {
    $exprobj = Expr-&gt;new(@$expr);
  } else {
    $exprobj = $expr;
  }
  return $exprobj-&gt;normalize($degree);
}

package AlgParserWithImplicitExpand;
@ISA=qw(AlgParser);

sub arraytoexpr {
  my ($self) = shift;
  my ($foo) = ExprWithImplicitExpand-&gt;fromarray(@_);
# print STDERR Data::Dumper-&gt;Dump([$foo],['retval']);
  return $foo;
}

package Expr;

sub new {
  my($class) = shift;
  my(@args) = @_;
  my($ret) = [@args];
  return (bless $ret, $class);
}

sub head {
  my($self) = shift;
  return ($self-&gt;[0]);
}


sub normalize {
#print STDERR "normalize\n";
#print STDERR Data::Dumper-&gt;Dump([@_]);

  my($self, $degree) = @_;
  my($class) = ref $self;
  $degree = $degree || 0;
  my($type, @args) = @$self;
  local $_;
  $_ = $type;
  my ($ret) = [$type, @args];


  if(/closep/) {
    $ret = $args[1]-&gt;normalize($degree);
  } elsif (/unop1/) {
    $ret = $class-&gt;new($type, $args[0], $args[1]-&gt;normalize($degree));
  } elsif (/binop/) {
    $ret = $class-&gt;new($type, $args[0], $args[1]-&gt;normalize($degree),
                             $args[2]-&gt;normalize($degree));
  } elsif (/func1/) {
    $args[0] =~ s/^arc/a/;
    $ret = $class-&gt;new($type, $args[0], $args[1]-&gt;normalize($degree));
  }


  if ($degree &lt; 0) {return $ret;}


  ($type, @args) = @$ret;
  $ret = $class-&gt;new($type, @args);
  $_ = $type;
  if (/binop1/ &amp;&amp; ($args[2]-&gt;[0] =~ 'unop1')) {
    my($h1, $h2) = ($args[0], $args[2]-&gt;[1]);
    my($s1, $s2) = ($h1 eq '-', $h2 eq '-');
    my($eventual) = ($s1==$s2);
    if ($eventual) {
      $ret = $class-&gt;new('binop1', '+', $args[1], $args[2]-&gt;[2] );
    } else {
      $ret = $class-&gt;new('binop1', '-', $args[1], $args[2]-&gt;[2] );
    }
  } elsif (/binop2/ &amp;&amp; ($args[1]-&gt;[0] =~ 'unop1')) {
    $ret = $class-&gt;new('unop1', '-',
                       $class-&gt;new($type, $args[0], $args[1]-&gt;[2],
                                   $args[2])-&gt;normalize($degree) );
  } elsif (/binop[12]/ &amp;&amp; ($args[2]-&gt;[0] eq $type) &amp;&amp;
                          ($args[0] =~ /[+*]/)) {
# Remove frivolous right-association
# For example, fix 3+(4-5) or 3*(4x)
    $ret = $class-&gt;new($type, $args[2]-&gt;[1],
                       $class-&gt;new($type, $args[0], $args[1],
                                   $args[2]-&gt;[2])-&gt;normalize($degree),
                       $args[2]-&gt;[3]);
  } elsif (/unop1/ &amp;&amp; ($args[0] eq '+')) {
    $ret = $args[1];
  } elsif (/unop1/ &amp;&amp; ($args[1]-&gt;[0] =~ 'unop1')) {
    $ret = $args[1]-&gt;[2];
  }
  if ($degree &gt; 0) {
  }
  return $ret;
}

sub tostring {
# print STDERR "Expr::tostring\n";
# print STDERR Data::Dumper-&gt;Dump([@_]);
  my($self) = shift;
  my($type, @args) = @$self;
  local $_;
  $_ = $type;
  /binop1/ &amp;&amp; do {
    my ($p1, $p2) = ('','');
    if ($args[2]-&gt;[0] eq 'binop1') {($p1,$p2)=qw{ ( ) };}
    return ($args[1]-&gt;tostring() . $args[0] . $p1 .
            $args[2]-&gt;tostring() . $p2);
  };
  /unop1/ &amp;&amp; do {
    my ($p1, $p2) = ('','');
    if ($args[1]-&gt;[0] =~ /binop1/) {($p1,$p2)=qw{ ( ) };}
    return ($args[0] . $p1 . $args[1]-&gt;tostring() . $p2);
  };
  /binop2/ &amp;&amp; do {
    my ($p1, $p2, $p3, $p4)=('','','','');
    if ($args[0] =~ /implicit/) {$args[0] = ' ';}
    if ($args[1]-&gt;[0] =~ /binop1/) {($p1,$p2)=qw{ ( ) };}
#    if ($args[2]-&gt;[0] =~ /binop[12]/) {($p3,$p4)=qw{ ( ) };}
    if ($args[2]-&gt;[0] =~ /binop[12]|unop1/) {($p3,$p4)=qw{ ( ) };}
    return ($p1 . $args[1]-&gt;tostring() . $p2 . $args[0] . $p3 .
            $args[2]-&gt;tostring() . $p4);
  };
  /binop3/ &amp;&amp; do {
    my ($p1, $p2, $p3, $p4)=('','','','');
#    if ($args[1]-&gt;[0] =~ /binop[123]|numberE/) {($p1,$p2)=qw{ ( ) };}
    if ($args[1]-&gt;[0] =~ /binop[123]|unop1|numberE/) {($p1,$p2)=qw{ ( ) };}
#    if ($args[2]-&gt;[0] =~ /binop[12]|numberE/) {($p3,$p4)=qw{ ( ) };}
    if ($args[2]-&gt;[0] =~ /binop[12]|unop1|numberE/) {($p3,$p4)=qw{ ( ) };}
    return ($p1 . $args[1]-&gt;tostring() . $p2 . $args[0] . $p3 .
            $args[2]-&gt;tostring() . $p4);
  };
  /func1/ &amp;&amp; do {
    return ($args[0] . '(' . $args[1]-&gt;tostring() . ')');
  };
  /special|varname|numberE?/ &amp;&amp; return $args[0];
  /closep/ &amp;&amp; do {
    my(%close) = %AlgParser::close;



    return ($args[0] . $args[1]-&gt;tostring() . $close{$args[0]});
  };
}

sub tolatex {
  my($self) = shift;
  my($type, @args) = @$self;
  local $_;
  $_ = $type;
  /binop1/ &amp;&amp; do {
    my ($p1, $p2) = ('','');
    if ($args[2]-&gt;[0] eq 'binop1') {($p1,$p2)=qw{ \left( \right) };}
    return ($args[1]-&gt;tolatex() . $args[0] . $p1 .
            $args[2]-&gt;tolatex() . $p2);
  };
  /unop1/ &amp;&amp; do {
    my ($p1, $p2) = ('','');
    if ($args[1]-&gt;[0] =~ /binop1/) {($p1,$p2)=qw{ \left( \right) };}
    return ($args[0] . $p1 . $args[1]-&gt;tolatex() . $p2);
  };
  /binop2/ &amp;&amp; do {
    my ($p1, $p2, $p3, $p4) = ('','','','');
    if ($args[0] =~ /implicit/) {
      if ( (($args[1]-&gt;head eq qq(number)) &amp;&amp;
            ($args[2]-&gt;head eq qq(number))) ||
           (($args[1]-&gt;head eq qq(binop2)) &amp;&amp;
            ($args[1]-&gt;[2]-&gt;head eq qq(number))) ) {
        $args[0] = '\\,';
      } else {
        $args[0] = ' ';
      }
    }
    if ($args[1]-&gt;[0] =~ /binop1|numberE/)
      {($p1,$p2)=qw{ \left( \right) };}
 #   if ($args[2]-&gt;[0] =~ /binop[12]|numberE/)
        if ($args[2]-&gt;[0] =~ /binop[12]|numberE|unop1/)
      {($p3,$p4)=qw{ \left( \right) };}
    if ($args[0] eq '/'){
#	return('\frac{' . $p1 . $args[1]-&gt;tolatex() . $p2 . '}'.
#               '{' . $p3 . $args[2]-&gt;tolatex() . $p4 . '}' );
        return('\frac{' . $args[1]-&gt;tolatex() . '}'.
               '{' . $args[2]-&gt;tolatex() . '}' ); 
    }
    else{
    return ($p1 . $args[1]-&gt;tolatex() . $p2 . $args[0] . $p3 .
            $args[2]-&gt;tolatex() . $p4);
    }
  };
  /binop3/ &amp;&amp; do {
    my ($p1, $p2, $p3, $p4)=('','','','');
#    if ($args[1]-&gt;[0] =~ /binop[123]|numberE/) {($p1,$p2)=qw{ \left( \right) };}
  if ($args[1]-&gt;[0] =~ /binop[123]|unop1|numberE/) {($p1,$p2)=qw{ \left( \right) };}
# Not necessary in latex
#   if ($args[2]-&gt;[0] =~ /binop[12]/) {($p3,$p4)=qw{ \left( \right) };}
    return ($p1 . $args[1]-&gt;tolatex() . $p2 . "^{" . $p3 .
            $args[2]-&gt;tolatex() . $p4 . "}");
  };
  /func1/ &amp;&amp; do {
      my($p1,$p2);
      if($args[0] eq "sqrt"){($p1,$p2)=qw{ \left{ \right} };}
      else {($p1,$p2)=qw{ \left( \right) };}

      #
      #  DPVC -- 2003/03/31
      #       added missing trig functions
      #
      #$specialfunc = '(?:abs|logten|asin|acos|atan|sech|sgn|step|fact)';
      $specialfunc = '(?:abs|logten|a(?:sin|cos|tan|sec|csc|cot)h?|sgn|step|fact)';
      #
      #  End DPVC
      #

      if ($args[0] =~ /$specialfunc/) {
         return ('\mbox{' . $args[0] .'}'. $p1 . $args[1]-&gt;tolatex() . $p2);
      }
      else {
        return ('\\' . $args[0] . $p1 . $args[1]-&gt;tolatex() . $p2);
      }
  };
  /special/ &amp;&amp; do {
    if ($args[0] eq 'pi') {return '\pi';} else {return $args[0];}
  };
  /varname|(:?number$)/ &amp;&amp; return $args[0];
  /numberE/ &amp;&amp; do {
    $args[0] =~ m/($AlgParser::numberplain)E([-+]?\d+)/;
    return ($1 . '\times 10^{' . $2 . '}');
  };
  /closep/ &amp;&amp; do {
    my($backslash) = '';
    my(%close) = %AlgParser::close;
    if ($args[0] eq '{') {$backslash = '\\';}
#This is for editors to match: }
    return ('\left' . $backslash . $args[0] . $args[1]-&gt;tolatex() .
            '\right' . $backslash . $close{$args[0]});
  };
}

sub fromarray {
  my($class) = shift;
  my($expr) = shift;
  if ((ref $expr) ne qq{ARRAY}) {
    die "Program error; fromarray not passed an array ref.";
  }
  my($type, @args) = @$expr;
  foreach my $i (@args) {
    if (ref $i) {
      $i = $class-&gt;fromarray($i);
    }
  }
  return $class-&gt;new($type, @args);
}

package ExprWithImplicitExpand;
@ISA=qw(Expr);


sub tostring {
# print STDERR "ExprWIE::tostring\n";
# print STDERR Data::Dumper-&gt;Dump([@_]);
  my ($self) = shift;

  my($type, @args) = @$self;

  if (($type eq qq(binop2)) &amp;&amp; ($args[0] eq qq(implicit))) {
    my ($p1, $p2, $p3, $p4)=('','','','');
    if ($args[1]-&gt;head =~ /binop1/) {($p1,$p2)=qw{ ( ) };}
#    if ($args[2]-&gt;head =~ /binop[12]/) {($p3,$p4)=qw{ ( ) };}
    if ($args[2]-&gt;head =~ /binop[12]|unop1/) {($p3,$p4)=qw{ ( ) };}
    return ($p1 . $args[1]-&gt;tostring() . $p2 . '*' . $p3 .
            $args[2]-&gt;tostring() . $p4);
  } else {
    return $self-&gt;SUPER::tostring(@_);
  }
}
</pre></body></html>