[R] How to make "<-" generic?

Richard A. O'Keefe ok at cs.otago.ac.nz
Mon Jul 28 02:45:52 CEST 2003


The model of assignment in R is pretty simple:

    (variable) <- (expression)
	Evaluate expression, store result in variable.
	This is core syntax.  A compiled implementation of this would
	not involve any function call.  The behaviour does not in any
	way depend on the prior value of (variable), indeed, there is
	no requirement that (variable) _have_ any value.

    func(arg, args) <- (expression)
	This is handled by macro-expansion to
	arg <- "func<-"(arg, args, value=(expression))
	(If arg is not a variable, the expansion is applied recursively.)

	This involves a perfectly ordinary function call (which happens
	to have a funny name) and a perfectly ordinary assignment.
	The behaviour of "func<-" may depend on the value of arg; it
	need not, and in that case arg need not have a value, thanks to
	lazy evaluation.  Note that "func<-" itself does not, as a rule,
	change any variable (other than its own).  The change is done
	by the ordinary assignment to arg.

	Example:
	"+<-" <- function(lhs, rhs, value) value - rhs
	Now
	x + 1 <- 3
	results in x being 2.

"<-" already *is* as generic as it can possibly be; it does the right
thing whatever the value of the right hand side and whatever the value
(including none) of the left hand side.

If you want a kind of assignment which does something different,
then there is no compelling reason to (ab)use "<-" to do it; you
could follow the example of ?assign and use a readable intention-revealing
function name to do whatever it is that you want, and it could exploit
lazy evaluation to determine the name of the variable(s) it is to affect.

If anyone succeeded in making "<-" act like a normal operator and then
made its behaviour depend on the value of its first argument, we would
be left with no simple way to *initialise* a variable.

Please, DON'T try to 'make "<-" generic'.




More information about the R-help mailing list