Here's a modification to my code above which handles adding fractions and printing out the partial results. Finishing it off is left as an exercise to the reader...
(1/2+2/3)
7/6

(1/2+(2/3+4/5))
(1/2+22/15)
59/30

((5/3+7/13)+(5/2+3/7))
(86/39+(5/2+3/7))
(86/39+41/14)
2803/546
#!/usr/bin/perl -w # # add fractions and display partial results # use re 'eval'; #use recursive regex for parsing use strict; our $num = qr{\d+(?:/\d+)?}; our $op = qr{[+*/\-]}; # an expression is a fraction or a pair of expressions separated by # an operator, enclosed in parens. our $exp; $exp = qr{$num|\(\s*(??{$exp})\s*$op\s*(??{$exp})\s*\)}s; # Something to test the evaluator with my @tests = ("(1/2+2/3)","(1/2+(2/3+4/5))","((5/3+7/13)+(5/2+3/7))"); for my $t (@tests) { print "$t\n"; print simplify($t,"",""); print "\n\n"; } sub simplify { my ($e, $pre, $post) = @_; if($e =~ /^($num)$/s) { return $1; } elsif ($e =~ /^\(($exp)\+($exp)\)$/s) { my ($l, $r) = ($1,$2); my $left = simplify($l,"",""); print "$pre($left+$r)$post\n" if $l!~m/^$num$/; my $right = simplify($r,"($left+",")"); print "$pre($left+$right)$post\n" if $r!~m/^$num$/; my $sum = add_frac($left, $right); return "$sum"; } elsif ($e =~ /^\(($exp)-($exp)\)$/s) { #subtraction } elsif ($e =~ /^\(($exp)\*($exp)\)$/s) { #multiplication } elsif ($e =~ /^\(($exp)\/($exp)\)$/s) { #division } else { die "Syntax error\n"; } } sub add_frac { my ($l, $r) = @_; my ($l_num, $l_denom) = $l =~ m{(\d+)/(\d+)}; my ($r_num, $r_denom) = $r =~ m{(\d+)/(\d+)}; my $denom = $l_denom * $r_denom; my $ans = $l_num * $r_denom + $r_num * $l_denom; return "$ans/$denom"; }


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

In reply to Re^2: Perl and maths by sleepingsquirrel
in thread Perl and maths by ReinhardE

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.