[R] Functions returning functions

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed May 20 13:48:56 CEST 2009


Paulo Grahl wrote:
> Dear All:
>
> I have a question regarding the behavior of functions.
> Say I define a function that returns another function :
> A <- function(parameters) {
>      # calculations w/ parameters returning 'y'
>      tmpf <- function(x) { # function of 'y' }
>      return(tmpf)
> }
>
> The value of the parameters are stored in an environment local to the
> function. 

consider this example:

    foo = function(a, b)
       function(c)
          if (c) a else b

    x = 1
    y = 2
    bar = foo(x, y)

    bar(TRUE)
    # 1
    x = 0
    bar(TRUE)
    # 1, not 0

    y = 0
    bar(FALSE)
    # 0, not 2

vQ




More information about the R-help mailing list