[Rd] Error "promise already under evaluation ..." with function(x, dim=dim(x))
Henrik Bengtsson
hb at biostat.ucsf.edu
Sat Nov 15 03:06:02 CET 2014
I've meant to ask the following for several years now. I understand why:
> foo <- function(x, dim=dim) { dim }
> foo(1)
Error in foo(1) :
promise already under evaluation: recursive default argument
reference or earlier problems?
gives an error, but why wouldn't/couldn't the following work?
> foo <- function(x, dim=dim(x)) { dim }
> foo(1)
Error in foo(1) :
promise already under evaluation: recursive default argument
reference or earlier problems?
As a workaround I also tried:
> foo <- function(x, dim) { if (missing(dim)) dim <- dim(x); dim }
> foo(1)
Error in foo(1) : argument "dim" is missing, with no default
which surprised me too.
For the first case, is the rationale related to:
> foo <- function(x, a=dim(x), dim) { a }
> foo(1)
Error in foo(1) : argument "dim" is missing, with no default
and
> foo <- function(x, a=dim(x), dim=a) { a }
> foo(1)
Error in foo(1) :
promise already under evaluation: recursive default argument
reference or earlier problems?
[since here argument 'dim' could take a function, e.g. foo(1,
dim=length)], and that R treats
foo <- function(x, dim=dim(x)) { dim }
in a similar way? That is, is R not "clever" enough to detect this as
a special case, but instead goes ahead and tries to evaluate the
default expression (=dim(x)) of argument 'dim' in order to get its
default value? If so, is there anything preventing R from support
this "special case", e.g. by evaluating the default expression without
argument/symbol 'dim' itself being in the picture to avoid "it finds
itself"? (Sorry if I'm using the incorrect words here).
Yes, I understand that I can do:
> foo <- function(x, dim=base::dim(x)) { dim }
> foo(1)
NULL
> foo <- function(x, dim=NULL) { if (is.null(dim)) dim <- dim(x); dim }
> foo(1)
NULL
or
> foo <- function(x, dim.=dim(x)) { dim. }
> foo(1)
NULL
but I would prefer not to have to turn those rather ad hoc solutions in my code.
Thanks,
Henrik
More information about the R-devel
mailing list