Understanding R functions lazy assessment

I am having trouble understanding why R has two functions below functionGen1and functionGen2behave differently. Both functions try to return another function that simply prints the number passed as an argument to the function generator.

In the first case, the generated functions do not work, because they are ano longer present in the global environment, but I do not understand why this should be. I would think that it was passed as an argument and replaced with aNumberin the namespace of the generator function and print function. A.

My question is: why the functions in the list list.of.functions1no longer work if anot defined in the global environment? (And why does this work for the occasion list.of.functions2and even list.of.functions1b)?

functionGen1 <- function(aNumber) {
  printNumber <- function() {
    print(aNumber)
  }
  return(printNumber)
}

functionGen2 <- function(aNumber) {
  thisNumber <- aNumber
  printNumber <- function() {
    print(thisNumber)
  }
  return(printNumber)
}

list.of.functions1 <- list.of.functions2 <- list()
for (a in 1:2) {
  list.of.functions1[[a]] <- functionGen1(a)
  list.of.functions2[[a]] <- functionGen2(a)
}

rm(a)

# Throws an error "Error in print(aNumber) : object 'a' not found"
list.of.functions1[[1]]()

# Prints 1
list.of.functions2[[1]]()
# Prints 2
list.of.functions2[[2]]()

# However this produces a list of functions which work
list.of.functions1b <- lapply(c(1:2), functionGen1)
+1
1

:

functionGen1 <- function(aNumber) {
  printNumber <- function() {
    print(aNumber)
  }
  return(printNumber)
}

a <- 1
myfun <- functionGen1(a)
rm(a)
myfun()
#Error in print(aNumber) : object 'a' not found

( , ), .

, , . myfun, aNumber = a. a , .

, functionGen2 , ,

functionGen1 <- function(aNumber) {
  force(aNumber)
  printNumber <- function() {
    print(aNumber)
  }
  return(printNumber)
}

a <- 1
myfun <- functionGen1(a)
rm(a)
myfun()
#[1] 1
+3

Source: https://habr.com/ru/post/1015607/


All Articles