Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top