Category talk:Wren-rat: Difference between revisions
m
→Source code: Now uses Wren S/H lexer.
m (→Source code: Added quotes to 'lang' attribute.) |
m (→Source code: Now uses Wren S/H lexer.) |
||
(8 intermediate revisions by the same user not shown) | |||
Line 1:
===Source code===
<syntaxhighlight lang="
import "./trait" for Comparable
Line 43:
static one { Rat.new( 1, 1) }
static two { Rat.new( 2, 1) }
static three { Rat.new( 3, 1) }
static four { Rat.new( 4, 1) }
static five { Rat.new( 5, 1) }
static six { Rat.new( 6, 1) }
static seven { Rat.new( 7, 1) }
static eight { Rat.new( 8, 1) }
static nine { Rat.new( 9, 1) }
static ten { Rat.new( 10, 1) }
static half { Rat.new( 1, 2) }
static third { Rat.new( 1, 3) }
static quarter { Rat.new( 1, 4) }
static fifth { Rat.new( 1, 5) }
static sixth { Rat.new( 1, 6) }
static seventh { Rat.new( 1, 7) }
static eighth { Rat.new( 1, 8) }
static ninth { Rat.new( 1, 9) }
static tenth { Rat.new( 1, 10) }
Line 87 ⟶ 101:
static fromString(s) {
var n
s = s.trim()
if (!(n = Num.fromString(s))) Fiber.abort("Argument must be a numeric string.")
if (n.isInteger) return Rat.new(n, 1)
return fromDecimalString_(s
}
Line 143 ⟶ 158:
truncate { Rat.fromInt(toFloat.truncate) } // lower integer, towards zero
round { Rat.fromInt(toFloat.round) } // nearer integer
roundUp { this >= 0 ? ceil : floor } // higher integer, away from zero
fraction { this - truncate } // fractional part (same sign as this.num)
Line 164 ⟶ 180:
pow(i) {
if (!((i is Num) && i.isInteger)) Fiber.abort("Argument must be an integer.")
if (i == 0) return
var np = _n.pow(i.abs).round
var dp = _d.pow(i.abs).round
return (i > 0) ? Rat.new(np, dp) : Rat.new(dp, np)
}
Line 174 ⟶ 192:
// Other methods.
inc { this + Rat.one } // increment
dec { this - Rat.one } // decrement
abs { (_n >= 0) ?
sign { _n.sign } // sign
// The inherited 'clone' method just returns 'this' as Rat objects are immutable.
Line 191 ⟶ 209:
}
// As above but compares the absolute values of the
compareAbs(other) { this.abs.compare(other.abs) }
Line 203 ⟶ 221:
toMixedString {
var q = _n / _d
var
return sign + q.toString + "_" + r.toString + "/" + _d.toString
}
|