Expressions and such

Peter Dalgaard BSA p.dalgaard@biostat.ku.dk
21 Apr 1998 20:11:45 +0200


Douglas Bates <bates@stat.wisc.edu> writes:

> For R it is still not clear to me how to manipulate the expressions
> and functions.  I saw some of the discussion about function closures
> and why it is not easy to coerce to a function but that is still black 
> magic to me.  I regret that I am not likely to be able to take the
> time to understand it better in the near future.

You could always take Bill V's approach of blatantly claiming "this
can't be done in R" and watching the reaction... ;)

<tutorial audience=anyone>

Expressions are fairly easy: Just mentally convert them to LISP to
access the parse tree. Convert everything to function calls and
represent each as a list with the first element being the function
name and the others being it's arguments. (This is not particularly
useful to people who don't know Lisp, I know.)

This little function gets you some of the way, although it won't do
things like tagged arguments (it can certainly be improved in other
ways too):

> dissect                                           
function (e) 
{
        level <<- level + 1
        cat(substring("||||||||||||||||", 1, level))
        cat(deparse(e), "\n")
        if (is.call(e) || is.expression(e)) 
                for (i in 1:length(e)) dissect(e[[i]])
        level <<- level - 1
}
> level<- -1
> dissect(expression(1+2+3*4))
1 + 2 + 3 * 4 
|1 + 2 + 3 * 4 
||+ 
||1 + 2 
|||+ 
|||1 
|||2 
||3 * 4 
|||* 
|||3 
|||4 

e.g. like LISP's (+(+ 1 2)(* 3 4)). 

This is all pretty much like S. What was the problem in the first place?

</tutorial>

Regarding function coercion, I'm still unconvinced why this shouldn't
be possible. I'd kind of like to keep the "everything is a list"
paradigm. Obviously, one cannot keep perfect S compatibility (because
of the environment/closure issue), but some way of constructing a
function from it's arguments, body, and environment would be useful.

Many things are in fact possible if you are sneaky enough, e.g. here's
a list.to.envir conversion:

environment(eval(expression(function(){}),envir=list(a=1,b=2))))

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)             FAX: (+45) 35327907

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel 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-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._