Skip to content
Prev 180928 / 398506 Next

*** POSSIBLE SPAM *** Functions returning functions

Paulo Grahl wrote:
no, see this:

 > f <- function( x = 3){
+    function( ){}
+ }
 > g <- f()
 > ls.str( environment(g) )
x :  num 3
 > h <- f(6)
 > ls.str( environment(h) )
x :  num 6
 > ls.str( environment(g) )
x :  num 3

See also colorRampPalette which uses this feature:

 > colorRampPalette
function (colors, ...)
{
    ramp <- colorRamp(colors, ...)
    function(n) {
        x <- ramp(seq.int(0, 1, length.out = n))
        rgb(x[, 1], x[, 2], x[, 3], maxColorValue = 255)
    }
}
<environment: namespace:grDevices>
 > pal <- colorRampPalette( c("blue", "white", "red") )
 > pal
function (n)
{
    x <- ramp(seq.int(0, 1, length.out = n))
    rgb(x[, 1], x[, 2], x[, 3], maxColorValue = 255)
}
<environment: 0x99aba4c>
 > ls.str( environment( pal ) )
colors :  chr [1:3] "blue" "white" "red"
ramp : function (x)