【发布时间】:2013-09-05 13:47:28
【问题描述】:
如何制作简单的泛型函数而又不使其过于复杂? 我想要这样的东西:
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)
}
但是没有更好的方法吗?
【问题讨论】:
-
classCheck看起来很像is和inherits函数。
标签: r methods generic-programming