Skip to content

Instantly share code, notes, and snippets.

@vsbuffalo
Created February 23, 2017 22:18
Show Gist options
  • Save vsbuffalo/ffc82f6c7274fb4e2db85dadcd944077 to your computer and use it in GitHub Desktop.
Save vsbuffalo/ffc82f6c7274fb4e2db85dadcd944077 to your computer and use it in GitHub Desktop.
library(purrr)
foo <- function(x) {
return(function(y) {
y + x
})
}
args <- list(1, 2)
foos_map <- map(args, foo)
foos_lapply <- lapply(args, foo)
foos_map[[1]](1)
# returns 3
foos_lapply[[1]](1)
# returns 2
foos_map[[1]](2)
# returns 4
foos_lapply[[1]](2)
# returns 3
@msuzen
Copy link

msuzen commented Feb 27, 2017

This is related to metaprogramming. Here is an old blog post, discussing a similar issue of generating lots of functions having similar templates: Metaprogramming in R with an example: Beating lazy evaluation. One way to resolve this is to use substitute. It is a bit verbose though without using purrr.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment