如何制作简单的泛型函数而又不使其过于复杂?我想要这样的东西:
inputA <- function(a,b){
return(structure(c(a=a,b=b), class= "inputclassA"))
}
inputB <- function(c,d){
return(structure(c(c=c,d=d), class= "inputclassB"))
}
mathstuff.inputclassA <- function(inp){
print("inputtype: inputclassA")
inp['a'] + inp['b']
}
mathstuff.inputclassB <- function(inp){
print("inputtype: inputclassB")
inp['c'] - inp['d']
}
mystructure <- inputA(4,2)
mathstuff(mystructure) #should return 6
mystructure <- inputB(4,2)
mathstuff(mystructure) #should return 4
到目前为止,我这样解决了
classCheck<-function(obj,checkIs){
return (attr(obj,"class") == checkIs)
}
但是没有更好的方法吗?