Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading for functions in R - strange behavior

Unfortunately things like (f+g)(3) where f and g are both unary functions do not work in R. Hence I tried to overload the "+" operator for unary functions in the following way:

"+.function" = function(e1, e2){
  return(function(x) e1(x) + e2(x))
}

But if I try to use this, this does nothing. The code

 a = function(x) 2*x
 (a+a)(2)

produces the same error as if +.function is not even defined.

By some time playing around I found out that there is in fact a possibility to add functions in this way: If the functions are member functions of an reference class, this works! I.e., the following code (together with the "+" definition from above)

clsA = setRefClass("clsA", 
  methods = list(
    b = function(x) 2*x
  ))

inst_a = clsA$new()
(inst_a$b + inst_a$b)(2)

returns "8" (as expected). Hence I already have some kind of a workaround for my problem. Now my questions are:

What is the reason for this strange behavior? Why doesn´t +.function care about "usual" function but class member functions? Has anyone an idea how "expand" the operator to usual functions?

like image 667
Patrick Roocks Avatar asked Mar 15 '13 12:03

Patrick Roocks


2 Answers

If you redifine the class of a, for example like class(a)<-"ownfunction" (or better yet class(a)<-c("ownfunction","function"), and make your "+.function" as "+.ownfunction", then (a+a)(2) works.

It seems that the function class is treated in some special way: If you run debug("+.function");(a+a)(2) you see that "+.function" is not even called.

EDIT: see comments.

like image 137
Jouni Helske Avatar answered Oct 20 '22 07:10

Jouni Helske


As a workaround, you could define a special operator (%...%) like this:

"%+%" <- function(e1, e2) {
  return(function(x) e1(x) + e2(x))
}

a <- function(x) 2*x
(a %+% a)(2) # == 8
like image 37
QkuCeHBH Avatar answered Oct 20 '22 07:10

QkuCeHBH