Skip to content

Instantly share code, notes, and snippets.

@hadley
Last active August 29, 2015 14:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadley/7f503b4a5ef404f0aad2 to your computer and use it in GitHub Desktop.
Save hadley/7f503b4a5ef404f0aad2 to your computer and use it in GitHub Desktop.
iclass <- function(x) {
c(
if (is.matrix(x)) "matrix",
if (is.array(x) && !is.matrix(x)) "array",
if (is.double(x)) "double",
if (is.integer(x)) "integer",
mode(x)
)
}
method_names <- function(generic, x) {
paste0(generic, ".", c(class(x), iclass(x), "default"))
}
s3_dispatch <- function(call) {
call <- substitute(call)
generic <- as.character(call[[1]])
object <- eval(call[[2]], parent.frame())
methods <- method_names(generic, object)
exists <- vapply(methods, exists, logical(1))
cat(paste0(ifelse(exists, "*", " "), " ", methods,
collapse = "\n"), "\n", sep = "")
}
x <- Sys.time()
s3_dispatch(print(x))
s3_dispatch(is.numeric(x))
s3_dispatch(as.Date(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment