Skip to content
Prev 180936 / 398506 Next

Functions returning functions

Romain Francois wrote:
... but there are ways around it

f <- function( x = 3 ){
    # y will be get a value the first time
    # the function created below is called
    delayedAssign( "y", {
        cat( "\nevaluating `y` right now\n" )
        x + 5
    } )
   
    # z will get a new value each time the function
    # created below is called
    makeActiveBinding( "z", function( data ){
        if( missing(data) ){
            cat( "\nevaluating `z` right now\n" )
            rnorm(x)
        }
    }, environment() )
       function( ){
          list( y, z )
       }
}

 > h <- f()
 > h()

evaluating `y` right now

evaluating `z` right now
[[1]]
[1] 8

[[2]]
[1]  1.0991189 -1.1033016 -0.5410733

 > h()

evaluating `z` right now
[[1]]
[1] 8

[[2]]
[1]  0.7102276 -0.6371956 -0.7703179

 > environment(h)[["z"]]

evaluating `z` right now
[1] -0.6713595  2.2006114  0.9335674
 > environment(h)[["z"]]

evaluating `z` right now
[1]  0.1243523  0.6178176 -0.9043380