6 method set
($self: Num
$value) { $.q
= $value; $self; };
7 multi method string
($self:) {$self.q
~ $self.abbreviation
; }
8 multi method string
($self: Num
$prec) {
9 return $self.q
.fmt
('%.' ~ $prec ~ 'f') ~ $self.abbreviation
;
12 method toBase
($self:) { $.q
* $self.baseFactor
}
13 method fromBase
($self:) { $.q
/ $self.baseFactor
}
15 method setFromBase
($self: Num
$value) { $.q
= $value / $self.baseFactor
; }
16 method baseFactor
() { 1; }
19 multi
sub infix
:<+> (Unit
$a, Unit
$b) {
20 die unless $a.type
eq $b.type
;
22 # wierd hack around a wierd error.
23 my $aVal = $a.toBase
();
24 my $bVal = $b.toBase
();
25 $new.setFromBase
( $aVal + $bVal);
29 multi
sub infix
:<-> (Unit
$a, Unit
$b) {
31 # wierd hack around a wierd error.
32 my $aVal = $a.toBase
();
33 my $bVal = $b.toBase
();
34 $new.setFromBase
( $aVal - $bVal);
38 class Distance is Unit
{ method type
() { 'distance'} }
40 multi
sub postfix
:<ft
> (Num
$value) { Feet
.new
().set
($value) }
41 class Feet is Distance
{
42 method abbreviation
() { "ft" };
43 method baseFactor
() { 0.3048 };
46 # not m, as that's taken by m//
47 multi
sub postfix
:<m
> (Num
$value) { Meter
.new
().set
($value) }
48 class Meter is Distance
{
49 method abbreviation
() { "m" };
50 # no base factor because it IS the base Unit
53 multi
sub postfix
:<km
> (Num
$value) { Kilometer
.new
().set
($value) }
54 class Kilometer is Distance
{
55 method abbreviation
() { "km" };
56 method baseFactor
() { 1000 };
59 multi
sub prefix
:<~> (Unit
$unit) { $unit.string
; }
60 #multi sub infix:<`> (Int $value, Unit $unit) { $unit.set($value); };
69 my $add = $feet + $meter;
72 my $add2 = $meter + $feet;
75 my $sub = $meter - $feet;
78 my $kilometer = 1000km
;
79 $add = $kilometer + 90ft
;