R - Function overloading
This is usually best done through optional arguments. For example:
g <- function(X, Y=FALSE) {
if (Y == FALSE) {
# do something
}
else {
# do something else
}
}
Check out the missing() function in R. For the function to still run, you need to reassign the missing variables before running the rest of the function. For example, this code:
overload = function(x,y) {
if (missing(y)) {
y = FALSE
}
if (y == FALSE) {
print("One variable provided")
} else {
print("Two variables provided")
}
}
overload(1)
overload(1, 2)
Will return:
> overload(1)
[1] "One variable provided"
> overload(1, 2)
[1] "Two variables provided"
Lastly, the missing() function is only reliable if you haven't altered the variable in question in the function.
EDIT, following clarification of the question in comments above:
From a quick glance at this page, it looks like Erlang allows you to define functions that will dispatch completely different methods depending on the arity of their argument list (up to a ...
, following which the arguments are optional/don't affect the dispatched method).
To do something like that in R, you'll probably want to use S4 classes and methods. In the S3 system, the method that is dispatched depends solely on the class of the first argument. In the S4 system, the method that's called can depend on the classes of an arbitrary number of arguments.
For one example of what's possible, try running the following. It requires you to have installed both the raster
package and the sp
package. Between them, they provide a large number of functions for plotting both raster and vector spatial data, and both of them use the S4 system to perform method dispatch. Each of the lines returned by the call to showMethods()
corresponds to a separate function, which will be dispatched when plot()
is passed x
and y
arguments that having the indicated classes (which can include being entirely "missing"
).
> library(raster)
> showMethods("plot")
Function: plot (package graphics)
x="ANY", y="ANY"
x="Extent", y="ANY"
x="Raster", y="Raster"
x="RasterLayer", y="missing"
x="RasterStackBrick", y="ANY"
x="Spatial", y="missing"
x="SpatialGrid", y="missing"
x="SpatialLines", y="missing"
x="SpatialPoints", y="missing"
x="SpatialPolygons", y="missing"
R sure does. Try, for an example:
plot(x = 1:10)
plot(x = 1:10, y = 10:1)
And then go have a look at how the function accomplishes that, by typing plot.default
.
In general, the best way to learn how implement this kind of thing yourself will be to spend some time poking around in the code used to define functions whose behavior is already familiar to you.
Then, if you want to explore more sophisticated forms of method dispatch, you'll want to look into both the S3 and S4 class systems provided by R.