【问题标题】:Generic method without class definition没有类定义的通用方法
【发布时间】: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 看起来很像 isinherits 函数。

标签: r methods generic-programming


【解决方案1】:

好的,知道了。

这是关键。真可惜,我没有意识到,the "related" thread 有答案。

mathstuff <- function(x,...) UseMethod("mathstuff")

所以这非常有效。对不起,我的错。

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"))
}  

#make generic function
mathstuff <- function(x,...) UseMethod("mathstuff")

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) 

mystructure <- inputB(4,2)
mathstuff(mystructure) 

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2019-06-24
    • 2021-01-30
    • 2020-09-10
    相关资源
    最近更新 更多