Skip to content

Instantly share code, notes, and snippets.

@skids
Created June 16, 2009 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skids/130824 to your computer and use it in GitHub Desktop.
Save skids/130824 to your computer and use it in GitHub Desktop.
Q:PIR{
loadlib $P0, 'rational'
};
class Rat {
has $.v is rw; # Should be $!v;
submethod BUILD () {
$!v = Q:PIR{
new $P0, 'Rational'
$P0 = 0
%r = $P0
};
}
submethod setv ($v) {
$!v = $v;
}
submethod getv () {
$!v;
}
submethod setv_r (Rat $r) {
self.setv($r.getv);
}
our method Str {
my $v = $!v;
Q:PIR{
$P0 = find_lex '$v'
$S0 = $P0
%r = box $S0
}
}
our multi method say (Rat $r:) {
$r.Str.say;
}
our multi method inc () {
my $v = $!v;
my $res = Rat.new();
$res.setv(Q:PIR{
$P0 = find_lex '$v'
inc $P0
%r = $P0
});
$res;
}
our multi method dec () {
my $v = $!v;
my $res = Rat.new();
$res.setv(Q:PIR{
$P0 = find_lex '$v'
dec $P0
%r = $P0
});
$res;
}
our multi method plus (Int $i) {
my $v = $!v;
my $res = Rat.new();
$res.setv(Q:PIR{
$P0 = find_lex '$v'
$P1 = find_lex '$i'
$I0 = $P1
new $P3, 'Rational'
$P3 = $P0 + $I0
%r = $P3
});
$res;
}
our multi method mult (Int $i) {
my $v = $!v;
my $res = Rat.new();
$res.setv(Q:PIR{
$P0 = find_lex '$v'
$P1 = find_lex '$i'
$I0 = $P1
new $P3, 'Rational'
$P3 = $P0 * $I0
%r = $P3
});
# Force recanonicalization
$res.inc();
$res.dec();
$res;
}
our multi method divd (Int $i) {
my $v = $!v;
my $res = Rat.new();
$res.setv(Q:PIR{
$P0 = find_lex '$v'
$P1 = find_lex '$i'
$I0 = $P1
new $P3, 'Rational'
$P3 = $P0 / $I0
%r = $P3
});
$res;
}
# hacky workaround until Parrot exposes these
our multi method nom () {
my $s = self.Str;
$s ~~ /(\d+)/;
+$/;
}
# hacky workaround until Parrot exposes these
our multi method nom (Int $i) {
my $n = int(self.nom());
my $r = self.divd($n);
$r = $r.mult($i);
self.setv_r($r);
}
# hacky workaround until Parrot exposes these
our multi method denom () {
my $s = self.Str;
$s ~~ /\d+\/(\d+)/;
+$/[0];
}
# hacky workaround until Parrot exposes these
our multi method denom (Int $i) {
my $n = int(self.denom());
my $r = self.mult($n);
$r = $r.divd($i);
self.setv_r($r);
}
}
my Rat $r = Rat.new(3,4);
$r.Str.say;
$r.say;
$r.plus(1).say;
$r.say;
my Rat $f;
$f = $r.plus(3);
$f.say;
$f = $f.plus(3);
$f.say;
$r.say;
$f = $f.divd(5);
$f.say;
$f.inc();
$f.say;
$f.dec();
$f.say;
$f = $f.mult(10);
$f.say;
$f = $f.divd(2);
$f.say;
$f = $f.divd(2);
$f.say;
$f = $f.divd(2);
$f.say;
$f = $f.mult(5);
$f.say;
$f = $f.mult(2);
$f.say;
$f = $f.divd(2);
$f.say;
$f.nom.say;
$f.nom(3);
$f.say;
$f.denom.say;
$f.denom(7);
$f.say;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment