2013-09-05 4 views
1

Как сделать простые общие функции, не делая это слишком сложным? Я хочу иметь что-то вроде этого:Общий метод без определения класса

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

Но не есть лучший способ?

+0

'classCheck' очень похож на функции' is' и 'inherits'. –

ответ

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) 
Смежные вопросы