From ggrothendieck at gmail.com  Wed Apr 20 19:49:52 2005
From: ggrothendieck at gmail.com (Gabor Grothendieck)
Date: Wed Apr 20 19:50:01 2005
Subject: [Rd] Overloading methods in R
In-Reply-To: <BAY17-F138DB205C684A882E69EF3D12B0@phx.gbl>
References: <BAY17-F138DB205C684A882E69EF3D12B0@phx.gbl>
Message-ID: <971536df050420104965297d30@mail.gmail.com>

On 4/20/05, Ali - <saveez@hotmail.com> wrote:
> (1) It seems to me that, generally, in R it is not possible to overload
> functions. Is that right?
> 
> (2) Assuming that the above is true, or partially true, is there any extra
> packages to handle overloading in R?
> 
> (3) Assuming (1) is TRUE and (2) is FALSE, can anyone provide some advice on
> developing some function that understand what the arguments are and then
> calls the right overloaded function?
> 
> It would be something like this:
> 
> overloadedFunction1 <- function(x) {};
> 
> overloadedFunction2 <- function(x, y) {};
> 
> theFunction <- function(...)
> {
>   # How to identify ... and call the right overloaded function?
> }

Here is an example using S3:

> 
> f <- function(x, y) UseMethod("f")
> 
> f.default <- function(x,y,z) {
+         if (missing(z)) {
+         class.x <- if (missing(x)) "missing" else class(x)
+         class.y <- if (missing(y)) "missing" else class(y)
+         .Class <- paste(class.x, class.y, sep = ".")
+         NextMethod("f", z = 1)
+ } else # real default method
+ if (!missing(x) && !missing(y)) paste(x,y) else "one missing"
+ }
> 
> f.missing.missing <- function(x, y, z) "both Missing"
> f.numeric.numeric <- function(x,y, z) paste(x, y)
> 
> f()
[1] "both Missing"
> f(1)
[1] "one missing"
> f(y=1)
[1] "one missing"
> f(1,1)
[1] "1 1"


[Rd] Overloading methods in R
Gabor Grothendieck