Re: [Rd] unexpected behaviour when defining a function

From: Prof Brian Ripley <ripley_at_stats.ox.ac.uk>
Date: Tue 12 Sep 2006 - 06:42:42 GMT

On Mon, 11 Sep 2006, Deepayan Sarkar wrote:

> Hi,
>
> I know S manuals used to warn against using the same names for a
> variable and a function, but I have never seen that cause problems in
> R, so I usually don't pay much attention to it.

But in this case you have a promise. (BTW, it can still cause problems in R, hence the following NEWS item for 2.4.0:

	Lookup for S3 methods is confined to functions: previously a
	non-function 'fun.class' could have masked a function of the
	same name.

)

Note that you do have to look at an object to find out if it is a function, and that means forcing promises, the problem here.

> Which is why the following behaviour came as a surprise:
>
> > bar <- function() 1
> > foo <- function(bar = bar()) {
> + bar
> + }
> > foo(9)
> [1] 9
> > foo()
> Error in foo() : recursive default argument reference
>
> Exactly what rule am I violating here?

That an argument default value cannot refer to the argument.

This is an argument with a default value that is relying on lazy evaluation. When you come to evaluate 'bar' it is a promise with value bar(). Evaluating that value looks up 'bar' from the evaluation frame of foo() and the first candidate it finds is the argument it is the process of evaluating, hence the message.

> The following gives a slightly different error, but I assume it has a
> similar origin:
>
> bar <- function() 1
> foo <- function(bar) {
> if (missing(bar)) bar <- bar()
> bar
> }
> foo()

It says

> Error in foo() : argument "bar" is missing, with no default

and that is caused by bar <- bar(): it is looking for argument bar (to see if it is a function which can be called) and that argument has no default. (I would have thought that one was clear enough.)

-- 
Brian D. Ripley,                  ripley@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Tue Sep 12 16:48:18 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 12 Sep 2006 - 19:30:07 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.