R: Functions that create functions

From MathWiki

An example of a function that creates a function is 'strip.custom' in 'library(lattice)':

> strip.custom
function (...) 
{
    args <- list(...)
    function(...) {
        dots <- list(...)
        do.call("strip.default", updateList(dots, args))
    }
}
<environment: namespace:lattice> 

> updateList
Error: object "updateList" not found 

> lattice:::updateList
function (x, val) 
{
    if (is.null(x)) 
        x <- list()
    modifyList(x, val)
}
<environment: namespace:lattice>

> modifyList
function (x, val) 
{
    stopifnot(is.list(x), is.list(val))
    xnames <- names(x)
    for (v in names(val)) {
        xv <- if (v %in% xnames && is.list(xv) && is.list(valv)) 
            modifyList(xv, valv)
        else valv
    }
    x
}
<environment: namespace:utils>


Note the following:

> ff = function( a = 2) function( ...) sum(...) + a
> ff()
function( ...) sum(...) + a
<environment: 0x066f63e0>
> ff()(4)
[1] 6
> ff(3)(4)
[1] 7

A variable used in the function that is not defined in the defining function is not resolved until execution:

> ff = function( a = 2) function( ...) sum(...) + a + x
> ff()
function( ...) sum(...) + a + x
<environment: 0x07208e80>
> x <- 100
> ff()
function( ...) sum(...) + a + x
<environment: 0x06ecdc60>
> ff(3)
function( ...) sum(...) + a + x
<environment: 0x072019f8>
> ff(3)(2)
[1] 105
> x <- 1000
> ff(3)(2)
[1] 1005
> rm(x)
> ff(3)(2)
Error in ff(3)(2) : object "x" not found