2
0
Fork 0
CVE/samplePackage/R/S3.R

41 lines
1.0 KiB
R

# Constructors
circle <- function(r) structure(list(r=r), class="circle")
rectangle <- function(a, b) {
# equivalent to > structure(list(a=a, b=b), class="rectangle")
x <- list(a=a, b=b)
class(x) <- "rectangle"
x # return
}
# generics (custom)
area <- function(shape) UseMethod("area")
diam <- function(shape) UseMethod("diam")
# methods (implementation)
print.circle <- function(circle, ...) with(circle, cat("< circle r =", r, ">\n"))
#' Computes area of a circle object
#'
#' @param circle Instance of a circle.
#'
#' @returns Area of the given \code{circle}.
#' @export
area.circle <- function(circle) with(circle, pi * r^2)
diam.circle <- function(circle) with(circle, 2 * r)
print.rectangle <- function(rect, ...) {
cat("<rectangle a =", rect$a, ", b =", rect$b, ">\n", set="")
}
area.rectangle <- function(rect) rect$a * rect$b
diam.rectangle <- function(rect) sqrt(rect$a^2 + rect$b^2)
# usage
circ <- circle(2)
rect <- rectangle(a = 1, b = 2)
print(area(circ))
print(diam(rect))
print(circ)
print(rect)