Created
February 23, 2017 22:37
-
-
Save jonocarroll/314d0bebe1eb0156043d8974e89652e4 to your computer and use it in GitHub Desktop.
Use the force(x), Vince
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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