Search code examples
rmethodsgeneric-programming

Generic method without class definition


How to make simple generic functions without making it too complicated? I want to have something like this:

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

So far I solved it like this

classCheck<-function(obj,checkIs){
  return (attr(obj,"class") == checkIs)
}

But isn't there a better way?


Solution

  • Okay, got it.

    This is the key. What a shame, I didn't realize, the "related" thread had the answer.

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

    So this works wonderfully. Sorry, my bad.

    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)