Skip to content

Instantly share code, notes, and snippets.

@zeehio
Created June 6, 2024 05:10
Show Gist options
  • Save zeehio/fce34c12a512ac1995995014eafb9536 to your computer and use it in GitHub Desktop.
Save zeehio/fce34c12a512ac1995995014eafb9536 to your computer and use it in GitHub Desktop.
Example using double dispatch on S3.
doubledispatch <- function(x,y) {
  z <- list()
  z_classes <- expand.grid(
  cl_x=class(x),
  cl_y=class(y)
  )
  z_classes$cl_z <- paste0(
    z_classes$cl_x,
    "_",
    z_classes$cl_y
  )
  class(z) <- z_classes$cl_z
  UseMethod("doubledispatch", z)
}

doubledispatch.numeric_numeric <- function(x,y) {
   paste0("num_num_", x, "_", y)
}

doubledispatch.numeric_character <- function(x,y) {
  paste0("num_chr",x,"_",y)
}

doubledispatch(4,5)
#> [1] "num_num_4_5"
doubledispatch(2,"a")
#> [1] "num_chr2_a"

Created on 2024-06-06 with reprex v2.1.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment