On 09/09/2010 6:27 AM, Lorenzo Isella wrote:> Dear All,
> I hope this is not too off-topic.
> I am wondering if there is any possibility to make an R code lazy i.e.
> to prevent it from calculating quantities which are not used in the code.
> As an example: you are in a rush to modify your code and at the end it
> ends up with "dead branches", let's say a sequence which is
calculated
> but not used in any following calculations, not printed on screen, not
> stored in a file etc...
> It would be nice to teach R to automagically skip its calculation when I
> run the script (at least in a non-interactive way).
> I know that such a situation is probably the result of bad programming
> habits, but it may arise all the same.
> If I understand correctly, what I am asking for is something different
> from any kind of garbage collection which would take place, if ever,
> only after the array has been calculated.
> Any suggestions (or clarifications if I am on the wrong track) are
> appreciated.
R does lazy evaluation of function arguments, so an ugly version of what
you're asking for is to put all your code into arguments, either as
default values or as actual argument values. For example:
f <- function(a = slow1, b = slow2, c = slow3) {
a
c
}
f()
will never calculate slow2, but it will calculate slow1 and slow3. The
other version of this is
f <- function(a,b,c) {
a
c
}
f(slow1, slow2, slow3)
The big difference between the two versions is in scoping: the first
one evaluates the expressions in the local scope of f, the second one
evaluates them in the scope of the caller.
Duncan Murdoch