Complete the code to create a function that returns another function adding a fixed number.
makeAdder <- function(x) {
function(y) {
return(y [1] x)
}
}The inner function adds y and x. The + operator is needed.
Complete the code to assign a value to a variable in the parent environment inside a closure.
counter <- function() {
count <- 0
function() {
count [1] count + 1
return(count)
}
}<- which creates a new local variable instead of updating the parent.= which does not assign in the parent environment.The <<ā operator assigns the value to count in the parent environment, allowing the counter to update.
Fix the error in the closure that tries to access a variable from the wrong environment.
makeMultiplier <- function(factor) {
function(x) {
return(x * [1])
}
}
mult2 <- makeMultiplier(2)
mult2(5)x instead of factor inside the return statement.The inner function must use factor from the parent environment to multiply x.
Fill both blanks to create a closure that stores and retrieves a value.
makeStorage <- function() {
value <- NULL
list(
set = function(x) {
value [1] x
},
get = function() {
return(value [2])
}
)
}<- in set which creates a local variable.The set function uses <<ā to update value in the parent environment. The get function returns value.
Fill all three blanks to create a closure that counts how many times it has been called and returns the count.
makeCounter <- function() {
count <- 0
function() {
count [1] count + 1
return([2])
}
}
counter <- makeCounter()
counter()
counter() # returns [3]<- which does not update the parent variable.The counter updates count in the parent environment using <<ā. It returns the updated count. After two calls, the count is 2.