Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Created February 23, 2017 22:37
Show Gist options
  • Save jonocarroll/314d0bebe1eb0156043d8974e89652e4 to your computer and use it in GitHub Desktop.
Save jonocarroll/314d0bebe1eb0156043d8974e89652e4 to your computer and use it in GitHub Desktop.
Use the force(x), Vince
library(purrr)
foo <- function(x) {
function(y) {
y + x
}
}
args <- list(1, 2)
foos_map <- map(args, foo)
foos_lapply <- lapply(args, foo)
foos_map[[1]](1)
#> [1] 3
foos_lapply[[1]](1)
#> [1] 2
foos_map[[1]](2)
#> [1] 4
foos_lapply[[1]](2)
#> [1] 3
get("x", envir=environment(foos_map[[1]]))
#> [1] 2
get("x", envir=environment(foos_map[[2]]))
#> [1] 2
get("x", envir=environment(foos_lapply[[1]]))
#> [1] 1
get("x", envir=environment(foos_lapply[[2]]))
#> [1] 2
## NOTE: force(x) ensures evaluation of x in that environment
## probably equivalently, just x
foo2 <- function(x) {
force(x) ## IMPORTANT!
function(y) {
y + x
}
}
args <- list(1, 2)
foos_map2 <- map(args, foo2)
foos_lapply2 <- lapply(args, foo2)
foos_map2[[1]](1)
#> [1] 2
foos_lapply2[[1]](1)
#> [1] 2
foos_map2[[1]](2)
#> [1] 3
foos_lapply2[[1]](2)
#> [1] 3
get("x", envir=environment(foos_map2[[1]]))
#> [1] 1
get("x", envir=environment(foos_map2[[2]]))
#> [1] 2
get("x", envir=environment(foos_lapply2[[1]]))
#> [1] 1
get("x", envir=environment(foos_lapply2[[2]]))
#> [1] 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment