Skip to content
Permalink
Browse files

Streamline Rational.floor/ceiling/Int

- use ternaries
- use Failure.new instead of fail, just returning the Failure directly
- set return value on signature for possible future optimization possibilities
- makes them about 10% faster
  • Loading branch information...
lizmat committed Dec 27, 2018
1 parent 11da0fb commit cf0a6eaa24ef3c63cc39b58ccb0db106bb6948bf
Showing with 27 additions and 16 deletions.
  1. +27 −16 src/core/Rational.pm6
@@ -54,27 +54,38 @@ my role Rational[::NuT = Int, ::DeT = ::("NuT")] does Real {
nqp::decont($!denominator)))
}

method floor(Rational:D:) {
$!denominator || fail X::Numeric::DivideByZero.new:
:details('when calling .floor on Rational');
$!denominator == 1
?? $!numerator
!! $!numerator div $!denominator
method floor(Rational:D: --> Int:D) {
$!denominator
?? $!denominator == 1
?? $!numerator
!! $!numerator div $!denominator
!! Failure.new(
X::Numeric::DivideByZero.new(
:details('when calling .floor on Rational')
)
)
}

method ceiling(Rational:D:) {
$!denominator || fail X::Numeric::DivideByZero.new:
:details('when calling .ceiling on Rational');
$!denominator == 1
?? $!numerator
!! ($!numerator div $!denominator + 1)
method ceiling(Rational:D: --> Int:D) {
$!denominator
?? $!denominator == 1
?? $!numerator
!! ($!numerator div $!denominator + 1)
!! Failure.new(
X::Numeric::DivideByZero.new(
:details('when calling .ceiling on Rational')
)
)
}

method Int() {
method Int(--> Int:D) {
$!denominator
?? self.truncate
!! fail X::Numeric::DivideByZero.new:
:details('when coercing Rational to Int')
?? self.truncate
!! Failure.new(
X::Numeric::DivideByZero.new(
:details('when coercing Rational to Int')
)
)
}

multi method Bool(::?CLASS:D:) { nqp::hllbool(nqp::istrue($!numerator)) }

0 comments on commit cf0a6ea

Please sign in to comment.
You can’t perform that action at this time.