4 ms·
R can handle the examples in the article with generic functions: oddsratio <- function(x, ...) UseMethod("oddsratio", x) oddsratio.integer <- f
by kkoncevicius 4y ago
R can handle the examples in the article with generic functions:
oddsratio <- function(x, ...) UseMethod("oddsratio", x)
oddsratio.integer <- function(a, b, c, d) (a * d) / (b * c)
oddsratio.numeric <- function(p1, p0) ((p1)/(1 - p1)) / ((p0)/(1 - p0))
oddsratio.matrix <- function(x) (x[1, 1] * x[2, 2]) / (x[1, 2] * x[2, 1])
Then:
oddsratio(12L, 6L, 2L, 29L) # 29
oddsratio(12/(12+2), 6/(6+29)) # 29
oddsratio(matrix(c(12,6,2,29), 2)) # 29
- civilized 4y agoThis works, but only because you can tell which function you need to call using only the first argument. A more compelling example for Julia would have to have two modes of operation where the first argument has the same type in both modes, but later arguments have different types.
- kkoncevicius 4y agoTrue, but in R (at least in S3) it's probably avoided by design because of default parameters. A short example: genericfun.type1 <- function(x, sub=1) x - sub genericfun.type2 <- function(x, y) sum(x, y) The single case can be differentiated: genericfun(x) But which function are we calling with: genericfun(x, y) I don't know about Julia and how it solves this. Maybe by not allowing to pass nameless optional arguments.
- disgruntledphd2 4y agoS4 can dispatch on multiple arguments, just like Julia (though it seems a lot more natural in Julia).
- Cosi1125 4y agosetMethod(myfun, signature = c("integer", "character"), ...) setMethod(myfun, signature = c("list", "data.frame", "logical"), ...) setMethod(myfun, signature = "foo", ...) This takes into account as many arguments as you wish.