Saturday, 15 May 2010

r - If function(x) can work, why would we need function()? -



r - If function(x) can work, why would we need function()? -

i understand how "function(x)" works, role of "function()" here?

z <- function() { y <- 2 function(x) { x + y } }

function keyword part of creation of function (in programming sense gilles describes in answer). other parts argument list (in parentheses) , function body (in braces).

in example, z function takes no arguments. returns function takes 1 argument (named x) (since r returns lastly evaluated statement homecoming value default). function returns argument x plus 2.

when z called (with no arguments: z()) assigns 2 y (inside functions variable scope, additional concept i'm not going into). creates function (without name) takes single argument named x, which, when called, returns argument x plus 2. anonymous function returned phone call z and, presumably, stored can called later.

see https://github.com/hadley/devtools/wiki/functions , https://github.com/hadley/devtools/wiki/functionals more give-and-take on passing around functions objects.

r

No comments:

Post a Comment