[R] Evaluation of defaults in functions

hadley wickham h.wickham at gmail.com
Fri Sep 29 17:34:59 CEST 2006


> There are not all that many other languages that use lazy evaluation.
> Those that do are for the most part pure or nearly pure functional
> languages--Haskell is probably the main example.  These go much
> further in their use of lazy evaluation than R.  For analogs of the R
> expressions
>
>          x <- f(x)
>         list(f(x))
>          x + f(x)
>
> only the last one is guaranteed to result in f being called. This
> makes many things conceptually cleaner and also automatically supports
> lazy data structures, which allows one to express things like infinite
> sequences.  Some of the downsides are a more complex (or at least
> very different) implementation and that I becomes very hard to reason
> about performance.  One of the reasons performance is hard to sort out
> is that it is (deliberately, because of the declarative nature of
> these languages) hard to know exactly when an evaluation will occur.

You can argue similarly that adding state (eg. functions with side
effects) increases the complexity of reasoning about the result of a
calculcation.


> Contrary to Hadley's comment R actually provides quite a lot of control since
> assignments are guaranteed to cause evaluation, e.g. in
>
>      g <- function(x) {
>          x <- x # forces evaluation
>          ...
>      }
>
> the argument is guaranteed to be evaluated.  The function force()
> makes this a little more readable (avoids the need for a comment).

Perhaps control wasn't the word I was looking for.  Most lazy
languages provide some way to force evaluation.  Assignments forcing
evaluation seems to be a disadvantage to me - I can't do anything with
a promise apart from evaluate it.

> Lazy data structures can be implemented in R on top of the limited
> lazy evaluation mechanism.  I experimented with this for fun a one
> point.  Some code is in http://www.stat.uiowa.edu/~luke/R/lazy/.  This
> is out of date but not too hard to fix.  Insuring memory efficiency is
> still a bit tricky; some comments are int he notes at this site.

Thanks, I will take a look at that.

Regards,

Hadley



More information about the R-help mailing list