I know that I can create a stateful function adder
using the factory function adder_maker
per the below:
adder_maker <- function() {x <- 0; function() {x <<- x+1; x}}
adder1 <- adder_maker()
adder1()
adder1()
environment(adder1)
The function increments as expected and sits in its own enclosing environment.
However, if I don't want to store the factory function in an intermediate variable, then the inner function ends up in the global environment.
adder2 <- function() {x <- 0; function() {x <<- x+1; x}}()
adder2()
adder2()
environment(adder2)
- Why doesn't adder2 get associated with the environment of its anonymous parent?
- If adder2 lives in the global environment, why does it return 1 (instead of
Error: object 'x' not found
, when attempting to evaluate RHS of the inner assignment,x+1
)? - Are there any other clever ways to create a function that behaves like adder1, without assigning a variable for the parent function?