[R] functional (?) programming in r

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Mon Nov 17 23:42:45 CET 2008


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



More information about the R-help mailing list