R-beta: Bug or feature?

Ross Ihaka ihaka at stat.auckland.ac.nz
Sun Aug 17 11:21:10 CEST 1997


> Bill Venables writes:
> Here is a difference between R-0.50-a3 and S that surprised me

This follows from the way we have implemented lazy evaluation.
Function arguments are "promises" to evaluate an expression
and return a value "if asked".  Evaluation happens only once
and because the "promise" remembers its value.


In the example,

	x <- 1:10
	test1 <-
	function (x, nam = deparse(substitute(x))) 
	{
		x <- x
		nam
	}
	test1(x)

the argument x is bound to a promise to evaluate the symbol
"x" in the calling environment.  If we were to call substitute
at this point we would be handed the expression part of the
promise (this is what substitute does in our universe).
However, the assignment

	x <- x

forces the evaluation of the promise and its value is
assigned to x.  Thus x is no longer bound to a promise,
but rather to the value of the promise - i.e. the result
of evaluating 1:10.  When substitute is called on this
we get this value.

This is certainly different from S and I implemented it this
way deliberately (I think it might even have been when R still
had Lisp syntax).

I think that if formal arguments to functions should forget that they
are arguments when they are assigned to.

I.e. the behavior of

	x <- 1:10
	substitute(x)

should not depend on whether x is a formal argument or not
for example, consider:

	f <- function(x)
	{
		x <- 1:10
		y <- 1:10
		cat(deparse(substitute(x)), "\n")
		cat(deparse(substitute(y)), "\n")
		invisible()
	}

	# (1) Now let's run S on it

	> z <- 7
	> f(z)
	z 
	c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 

I think this is pretty weird, but look what happens when the
actual argument is a constant.

	# (2)

	> f(7) 
	c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 
	c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 

Why isn't the first line here just 7, since that was the actual
argument?

Anyway, I decided this was a bug and I fixed it!

We could change things so that things would work like (1) (we'd lose
some efficiency though), but it would be hard to make both (1) and (2)
work.
	Ross
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=



More information about the R-help mailing list