This is a virtual class to be contained in other class definitions. It can be used to define binary operators, e.g. +
or -
, inside an aoos class definition (defineClass
).
At the moment you can define binary operators as methods by naming them as .<binaryOperator>
(see the example). This is implemented for the following operators: +, -, *, /, %%, ^, <, >, ==, >=, <=, &
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | Rational <- defineClass("Rational", contains = c("Show", "Binary"), {
numer <- 0
denom <- 1
.g <- 1
.gcd <- function(a, b) if(b == 0) a else Recall(b, a %% b)
init <- function(numer, denom) {
.self$.g <- .gcd(numer, denom)
.self$numer <- numer / .g
.self$denom <- denom / .g
}
show <- function() {
cat(paste0(.self$numer, "/", .self$denom, "\n"))
}
".+" <- function(that) {
Rational(numer = numer * that$denom + that$numer * denom,
denom = denom * that$denom)
}
neg <- function() {
Rational(numer = -.self$numer,
denom = .self$denom)
}
".-" <- function(that) {
.self + that$neg()
}
})
rational <- Rational(2, 3)
rational + rational
rational$neg()
rational - rational
|
4/3
-2/3
0/1
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.