Re: [R] functional (?) programming in r

From: Thomas Lumley <>
Date: Mon, 17 Nov 2008 14:41:33 -0800 (PST)

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 Lumley			Assoc. Professor, Biostatistics	University of Washington, Seattle

______________________________________________ mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Mon 17 Nov 2008 - 22:43:36 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 17 Nov 2008 - 23:30:28 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive