Skip to content

map and lazy evaluation #191

@mplourde

Description

@mplourde
library(purrr)
packageVersion('purrr')
# [1] '0.2.1.9000'

This is an issue I encountered with newer releases of purrr when using map to wrap functions. map in prior versions of purrr didn't have this issue, but I'm not sure when the change occurred. Consider the following example where I create a list of functions and then wrap them with lapply:

funs <- list(
    function() message('fun1'),
    function() message('fun2'),
    function() message('fun3')
)

wrapper <- function(fun) {
    function() fun()
}

. <- funs %>%
    lapply(wrap_fun) %>% 
    invoke_map()
# fun1
# fun2
# fun3

When I perform this task with map:

. <- funs %>% 
    map(wrapper) %>%
    invoke_map()
# fun3
# fun3
# fun3

forceing the fun argument of wrapper fixes the issue:

forced_wrapper <- function(fun) {
    force(fun)
    function() fun()
}

. <- funs %>% 
    map(forced_wrapper) %>%
    invoke_map()
# fun1
# fun2
# fun3

Since map basically supplants lapply, it would be helpful if they behaved the same in this respect.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions