Operator overloading for functions in R - strange

2019-04-06 12:06发布

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?

2条回答
smile是对你的礼貌
2楼-- · 2019-04-06 12:42

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
查看更多
做个烂人
3楼-- · 2019-04-06 13:00

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.

查看更多
登录 后发表回答