-
-
Save bbkr/3048373 to your computer and use it in GitHub Desktop.
Having fun with currencies in Perl 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment