如何在闭包内重新定义 ‘+’?

huangapple go评论58阅读模式
英文:

How can I redefine '+' inside of a closure?

问题

首先,我知道这是愚蠢的,实际情况下永远不应该这样做。我也知道,即使在实践中这样做,你应该使用面向对象编程。我只是在这里为了证明一个观点。

我想重新定义 +。我想让下面这段代码工作:

'+' <- function(x, y) x + y + 2

允许像下面这样的代码:

2 + 2

返回 6

目前,它不起作用,因为它会导致无限递归。为了解决这个问题,我想使用闭包,但我不知道该怎么做。显然,我想要类似这样的东西:

SillyPlusGenerator <- function() {'+' <- function(x, y) x + y + 2}

但这不会让我在重新定义 + 的环境中计算 2 + 2,也不会告诉 SillyPlusGenerator 在父环境中查找 +。我知道我可以尝试使用 eval 并直接使用环境,但我确信闭包就是我所需要的。我错过了哪一步?

英文:

First of all, I know that this is stupid and never should be done in practice. I also know that even when doing it in practice, you ought to do it with OOP. I'm just doing it to prove a point.

I want to redefine &#39;+&#39;. I want

&#39;+&#39; &lt;- function(x, y) x + y + 2

to work. Allowing for code like

2 + 2

to return 6.

Currently, it doesn't work because it causes an infinite recursion. To solve this, I want to use a closure, but I'm at a loss as to how. I obviously want something like:

SillyPlusGenerator &lt;- function() {&#39;+&#39; &lt;- function(x, y) x + y + 2}

but that doesn't give me a way to evaluate 2 + 2 in an environment where + is redefined and it doesn't tell SillyPlusGenerator to look up + in the parent environment. I know that I could play around with eval and use environments directly, but I feel sure that closures are all that I need.

What step have I missed?

答案1

得分: 1

以下是翻译好的部分:

"The answer shows a couple of quick ways To solve this, but does not attempt to use closures.

To avoid the infinite recursion, you can:

  • Call the normal base R + function explicitly within the custom function (noting that + can be called as you would with a standard function e.g. +(2,2)).
`+` <- function(x, y) (base::`+`)((base::`+`)(x, y), 2) 

# and a variation of:
`+` <- function(x, y) Reduce(base::`+`, c(x, y, 2))
  • Redefine the + function within the custom function
`+` <- function(x, y) { `+` = base::`+` ; x + y + 2}

"

英文:

The answer shows a couple of quick ways "To solve this", but does not attempt to use closures.

To avoid the infinite recursion, you can:

  • Call the normal base R <code>`+`</code> function explicitly within the custom function (noting that <code>`+`</code> can be called as you would with a standard function e.g. <code>`+`(2,2)</code>).
`+` &lt;- function(x, y) (base::`+`)((base::`+`)(x, y), 2) 

# and a variation of:
`+` &lt;- function(x, y) Reduce(base::`+`, c(x, y, 2))
  • Redefine the <code>`+`</code> function within the custom function
`+` &lt;- function(x, y) { `+` = base::`+` ; x + y + 2}

huangapple
  • 本文由 发表于 2023年5月28日 22:06:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76351889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定