From michael.weylandt at gmail.com  Tue Feb 24 19:26:33 2015
From: michael.weylandt at gmail.com (Michael Weylandt)
Date: Tue, 24 Feb 2015 13:26:33 -0500
Subject: [Rd] iterated lapply
In-Reply-To: <alpine.DEB.2.02.1502240950150.2336@luke-Latitude>
References: <mailman.21.1424775604.19275.r-devel@r-project.org>
	<20150224113908.GA7612@cs.toronto.edu>
	<alpine.DEB.2.02.1502240950150.2336@luke-Latitude>
Message-ID: <4346B4DF-036F-4594-96C0-F8D3121427D0@gmail.com>


> On Feb 24, 2015, at 10:50 AM, <luke-tierney at uiowa.edu> wrote:
> 
> The documentation is not specific enough on the indented semantics in
> this situation to consider this a bug. The original R-level
> implementation of lapply was
> 
>    lapply <- function(X, FUN, ...) {
>        FUN <- match.fun(FUN)
>        if (!is.list(X))
>        X <- as.list(X)
>        rval <- vector("list", length(X))
>        for(i in seq(along = X))
>        rval[i] <- list(FUN(X[[i]], ...))
>        names(rval) <- names(X)           # keep `names' !
>        return(rval)
>    }
> 
> and the current internal implementation is consistent with this. With
> a loop like this lazy evaluation and binding assignment interact in
> this way; the force() function was introduced to help with this.
> 
> That said, the expression FUN(X[[i]], ...) could be replaced by
> 
>    local({
>        i <- i
>        list(FUN(X[[i]], ...)
>    })
> 
> which would produce the more desirable result
> 
>    > sapply(test, function(myfn) myfn(2))
>    [1] 2 4 6 8
> 

Would the same semantics be applied to parallel::mclapply and friends?

sapply(lapply(1:4, function(c){function(i){c*i}}), function(f) f(2))

# [1] 8 8 8 8

sapply(mclapply(1:4, function(c){function(i){c*i}}), function(f) f(2))

# [1] 6 8 6 8

I understand why they differ, but making mclapply easier for 'drop-in' parallelism might be a good thing. 

Michael


[Rd] iterated lapply
Michael Weylandt