Search code examples
rclosures

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


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 '+'. I want

'+' <- 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 <- function() {'+' <- 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?


Solution

  • 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}