Created
May 9, 2014 15:29
-
-
Save wch/7bb50e22d873da689b05 to your computer and use it in GitHub Desktop.
Non-reference class in R with class methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Class6 <- function(...) { | |
structure(list(...), class = "Class6") | |
} | |
# Methods for the class | |
Class6_methods <- list( | |
sum_xy = function(self) { | |
self$x + self$y | |
}, | |
inc_x = function(self, amount = 1) { | |
self$x <- self$x + amount | |
self | |
} | |
) | |
# Redefine $ so that you can use it to invoke class methods | |
`$.Class6` <- function(x, name) { | |
# This is a little crude, but it works | |
if (name %in% names(x)) { | |
res <- .subset2(x, name) | |
if (is.function(res)) { | |
# If it's a function, curry it | |
function(...) res(x, ...) | |
} else { | |
res | |
} | |
} else if (name %in% names(Class6_methods)) { | |
# Return a curried function | |
fun <- Class6_methods[[name]] | |
function(...) fun(x, ...) | |
} else { | |
stop('Member and method with name ', name, ' not found.') | |
} | |
} | |
`[[.Class6` <- `$.Class6` | |
# Create a new object z, which also has an individual method | |
z <- Class6( | |
x=1, | |
y=2, | |
prod_xy = function(self) self$x * self$y | |
) | |
z | |
z$x | |
z$sum_xy() | |
z$inc_x | |
z$inc_x()$inc_x(4) | |
z$sum_xy() | |
z <- z$inc_x()$inc_x(4) | |
z$sum_xy() | |
z$prod_xy() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment