Creating a list of functions using a loop in R -
in this introduction functional programming, author hadley wickham creates following function factory:
power <- function(exponent) { function(x) { x ^ exponent } }
he shows how function can used define other functions, such
square <- power(2) cube <- power(3)
now suppose wanted create these functions simultaneously via following loop:
ftns <- lapply(2:3, power)
this doesn't seem work, 3 gets assigned exponent entries of list:
as.list(environment(ftns[[1]])) $exponent [1] 3
can please me understand what's wrong code?
thanks!
what you're seeing consequence of r's use of promises implement lazy argument evaluation. see promise objects.
the problem in power()
function exponent
argument never evaluated, meaning underlying promise never called (at least not until generated function evaluated).
you can force promise evaluated this:
power <- function(exponent) { exponent; function(x) x^exponent; }; ftns <- lapply(2:3,power); sapply(ftns,function(ftn) environment(ftn)$exponent); ## [1] 2 3
without exponent;
statement force evaluation of promise, see issue:
power <- function(exponent) { function(x) x^exponent; }; ftns <- lapply(2:3,power); sapply(ftns,function(ftn) environment(ftn)$exponent); ## [1] 3 3
aha! r changelog shows behavior changed in 3.2.0:
* higher order functions such apply functions , reduce() force arguments functions apply in order eliminate undesirable interactions between lazy evaluation , variable capture in closures. resolves pr#16093.
it's classified new feature.
Comments
Post a Comment