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

From: Thomas Lumley <tlumley_at_u.washington.edu>
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

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley_at_u.washington.edu	University of Washington, Seattle

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html 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 https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive