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

From: Wacek Kusnierczyk <>
Date: Mon, 17 Nov 2008 23:42:45 +0100

Stavros Macrakis wrote:
> Wacek,
> I think when people say that R semantics are derived from Scheme, all
> they mean is that R supports lexical closures. But R has other
> features which are very un-Scheme-like, and when they interact with
> lexical closures, you get behavior you don't find in other functional
> languages.
> R passes function arguments using a "promise" mechanism somewhat
> similar to Algol 60's call-by-name, but caching the result when it is
> evaluated, what is sometimes called call-by-need. If the argument
> value is not needed, it keeps it as a "promise" (what Algol 60 called
> a "thunk").

that's somewhat of a mixture of call-by-name and call-by-need; from the former you get the actual argument expression, from the latter memoization of the value.

> Thus, we have:
> lapply(1:5,function(i) function( ) i )[[1]]() => 5
> since the inner i is actually bound to a 'promise' which seems to
> point to the variable used by lapply for counting.

indeed, for every function on the list there is a distinct promise, but the promise has no value until you actually call the function. looks like lapply uses one mutable variable which is referred to by all those promises, so all of them get 5 when forced.

> Compare with the result of:
> lapply(1:5,function(i) { i<-i; function() i } )[[1]]() => 1

yepp! though one might expect that the 'function() i' bit would actually enforce the promise at that stage.

> Scheme of course does not have the "promise" mechanism so this doesn't happen.

well, scheme does have a promise mechanism with delay and force, but you have to use it explicitly.

> I'm new to R, so I don't know if this is considered a bug or a feature.

i haven't seen any docs page that would explain such cases, so it's hard to judge for me. this might be an unforeseen side effect of the intended behaviour of the promise mechanism.

vQ mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Mon 17 Nov 2008 - 22:45:47 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 Tue 18 Nov 2008 - 01:30:26 GMT.

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

list of date sections of archive