Hadley Wickham on behalf of The R Consortium Working Group on OOP https://rconsortium.github.io/OOP-WG/R7:Afirst look at a new OOP system for RJune 2022
View Slide
bizarro< -function(x) {if (is.numeric(x)) {-x} else if (is.logical(x)) {!x} else if (is.character(x)) {str_reverse(x)} else if (is.factor(x)) {levels(x)< -rev(level(x))x} else {stop("Not supported")}}Why do we need OOP?This is even moreimportant for functionsin base R, like print()
S3S4English Fairy Tales (1918) by Flora Annie Steel, illustrated by Arthur RackhamR7 R7 = S3 + S4
library(R7)bizarro< -new_generic("bizarro", "x")With R7, wefirst define a genericName of the genericName of the argument used for dispatch
method(bizarro, class_numeric)< -function(x) {-x}method(bizarro, class_logical)< -function(x) {!x}method(bizarro, class_character)< -function(x) {str_reverse(x)}Then we define methodsName of the generic Built-in class
bizarro#> function (x,. . .) with 4 methods:#> 1:method(bizarro, "integer")#> 2:method(bizarro, "double")#> 3:method(bizarro, "character")#> 4:method(bizarro, "logical")
bizarro(1)#> [1] -1bizarro(TRUE)#> [1] FALSEbizarro(mean)#> Error: generic `bizarro()` can't find method#> for function object
Generics define behaviourClasses define data
range< -new_class("range",properties = list(start = class_numeric,end = class_numeric))Creating a new className of the classProperty typeProperty nameConstructor function
x< -range(start = 1, end = 10)x#> #> @ start: num 1#> @ end : num 10[email protected][email protected]< -20[email protected]< -"x"#> Error: @end must be , not
r< -range(start = 10, end = 1) #> #> @ start: num 10#> @ end : num 1But…
range< -new_class("range",properties =. . .,validator = function(self) {if (length([email protected])! =1) {"@start must be length 1"} else if (length([email protected])! =1) {"@end must be length 1"} else if ([email protected] < [email protected]) {"@end must be greater than or equal to @start"}})Can add a validator to prevent that from happening
range< -new_class("range",properties = list(start = class_double,end = class_double,length = new_property(getter = function(self) [email protected] - [email protected],)),…)Can also create dynamic properties
S3S4English Fairy Tales (1918) by Flora Annie Steel, illustrated by Arthur RackhamR7
1. Team effort.2. Formal definition of class andproperties (like S4).3. Embrace data access.4. Backward compatible with S3.5. Pit of success.Why do we hope this will succeed?
Please try it out!https://rconsortium.github.io/OOP-WG/remotes: :install_github("rconsortium/OOP-WG")What doesn’t work? What don’t you understand?These slides at https://speakerdeck.com/hadley/r7-a-first-look