[R] functional (?) programming in r

Thomas Lumley tlumley at u.washington.edu
Mon Nov 17 23:41:33 CET 2008


On Mon, 17 Nov 2008, Wacek Kusnierczyk wrote:

> the following is a trivialized version of some functional code i tried
> to use in r:
>
> (funcs = lapply(1:5, function(i) function() i))
> # a list of no-parameter functions, each with its own closure environment,
> # each supposed to return the corresponding index when applied to no
> arguments
>
> sapply(funcs, function(func) func())
> # supposed to return c(1,2,3,4,5)
>
> there is absolutely nothing unusual in this code, in the context of
> functional programming.

What is unusual is R's lazy evaluation. Each function gets a promise to 
evaluate i, but the promise isn't forced until i is 5.  Lazy evaluation is 
sometimes confusing, but it's the price R pays for not having macros.

If you want to get around this (rather than just to construct an example), 
use force().

(funcs = lapply(1:5, function(i) {force(i);function() i}))


 	-thomas

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle



More information about the R-help mailing list