In this introduction to functional programming, the author Hadley Wickham creates the following function factory:
power <- function(exponent) {
function(x) {
x ^ exponent
}
}
He then shows how this function can be used to define other functions, such as
square <- power(2)
cube <- power(3)
Now suppose I wanted to create these functions simultaneously via the following loop:
ftns <- lapply(2:3, power)
This doesn't seem to work, as 3 gets assigned to the exponent for all entries of the list:
as.list(environment(ftns[[1]]))
$exponent
[1] 3
Can someone please help me understand what's wrong with this code?
Thanks!