Skip to content
Prev 49670 / 63421 Next

Closing over Garbage

On Thu, 15 Jan 2015, Christian Sigg wrote:

            
R's semantics do not permit this sort of optimization in general --
there may be something we could do if users could provide annotations
that allow the semantics to be relaxed; that sort of thing is being
considered but won't be available anytime soon.

The approach I use in situations like this is to write top-level
functions that create closures. So for your example, replace

  linearise <- function(x) {
     x^gamma
  }

with

  makeLinearize(x, gamma),

where makeLinearize is defined at top level as

makeLinearize <- function(x, gamma) {
     function(x) {
         x^gamma
     }
}

Best,

luke