对R中的函数的操作符重载奇怪的行为 [英] Operator overloading for functions in R - strange behavior
问题描述
不幸的是像(f + g)(3)
其中f和g都是一元函数在R中不工作。因此我试图重载+运算符用于一元函数:
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)
产生与 +。function
不同的错误甚至定义。
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)
返回8因此,我已经有一些解决我的问题的解决方法。现在我的问题是:
returns "8" (as expected). Hence I already have some kind of a workaround for my problem. Now my questions are:
这种奇怪行为的原因是什么?为什么不 +。function
关心通常函数,但类成员函数?有没有人知道如何扩展操作符到通常的功能?
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?
推荐答案
如果你重新定义 a (例如
,并使你的 class(a)< - ownfunction
< -c(ownfunction,function)+。function
as + .ownfunction
,然后(a + a)(2)
工作。
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.
<<>看起来函数
类以某种特殊方式处理:如果运行 debug(+。function); + a)(2)
你会看到+。function
甚至不被调用。
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.
编辑:见注释。
这篇关于对R中的函数的操作符重载奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!