Skip to content

Commit

Permalink
Add some gcd using routines, and infix:<FR+>. The latter is supposed …
Browse files Browse the repository at this point in the history
…to be infix:<+>, but that's not working at the moment.
  • Loading branch information
colomon committed Feb 4, 2011
1 parent 4b73620 commit ffa4f15
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
12 changes: 9 additions & 3 deletions lib/Math/FatRat.pm
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ class Math::FatRat does Real {
:denominator(Math::BigInt.new($r.denominator)));
}

multi method new(Math::BigInt $numerator is copy, Math::BigInt $denominator is copy) {
# MUST: add GCD calculation here!!!!
self.bless(*, :numerator($numerator), :denominator($denominator));
multi method new(Math::BigInt $numerator, Math::BigInt $denominator) {
my $gcd = gcd($numerator, $denominator);
self.bless(*, :numerator($numerator div $gcd), :denominator($denominator div $gcd));
}

# multi method new(Int $numerator is copy, Int $denominator is copy) {
Expand Down Expand Up @@ -54,6 +54,12 @@ class Math::FatRat does Real {
method pred {
Math::FatRat.new($!numerator - $!denominator, $!denominator);
}

multi sub infix:<FR+>(Math::FatRat $a, Math::FatRat $b) is export(:DEFAULT) {
my $gcd = gcd($a.denominator, $b.denominator);
Math::FatRat.new($a.numerator * ($b.denominator div $gcd) + $b.numerator * ($a.denominator div $gcd),
($a.denominator div $gcd) * $b.denominator);
}
}

# multi sub prefix:<->(Math::FatRat $a) {
Expand Down
6 changes: 5 additions & 1 deletion t/01-basics.t
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ plan *;
is ~$b.nude, ~<59 2>, "and the original is unchanged";
}


{
my $a = Math::FatRat.new(6L,9L);
isa_ok $a, Math::FatRat, "Two BigInt .new yields a FatRat";
is ~$a.nude, ~<2 3>, "and fraction is properly reduced";
}

done;
14 changes: 14 additions & 0 deletions t/02-arith.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use Math::FatRat;
use Math::BigInt;
use Test;

plan *;

{
my $a = Math::FatRat.new(1/3) FR+ Math::FatRat.new(1/6);
isa_ok $a, Math::FatRat, "infix:<+> creates a FatRat";
is ~$a.nude, ~<1 2>, "and it's 1/2";
}


done;

0 comments on commit ffa4f15

Please sign in to comment.