Skip to content

Instantly share code, notes, and snippets.

@masak
Created July 4, 2012 16:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save masak/3048087 to your computer and use it in GitHub Desktop.
Save masak/3048087 to your computer and use it in GitHub Desktop.
Having fun with currencies in Perl 6
enum Currency <EUR USD>;
multi rate(EUR) { 1.252 }
multi rate(USD) { 1.000 }
class Money {
has Real $.amount;
has Currency $.currency;
method convert_to(Currency $currency) {
my $self-rate = rate $.currency;
my $other-rate = rate $currency;
my $amount = $.amount * $self-rate / $other-rate;
Money.new(:$amount, :$currency);
}
method Str() {
"$.amount $.currency"
}
}
sub postfix:<EUR> { Money.new(:$^amount, :currency(EUR)) }
sub postfix:<USD> { Money.new(:$^amount, :currency(USD)) }
my $money = 1000\ EUR;
say "$money is $money.convert_to(USD)";
@andydude
Copy link

andydude commented Jul 4, 2012

Neat!

@bbkr
Copy link

bbkr commented Jul 4, 2012

Awesome idea!

@rightfold
Copy link

Use BigRat, not Real.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment