[Rd] Capturing the expression representing the body of a function

Hadley Wickham hadley at rice.edu
Tue May 3 00:19:06 CEST 2011


> The body of a function isn't an expression, it's a language object.  A
> language object is represented internally as a pairlist, while an expression
> is represented as a generic vector, i.e. the thing that list() gives.

That doesn't agree with the documentation of is.language which implies
a language object is "a ‘name’, a ‘call’, or an ‘expression’", and
doesn't mention pairlist anywhere.

> Your 1st try gives you the language object.

It gives me a call, doesn't it?  And the documentation for body
implies that this special type of call is called a bracketed
expression (despite it not being an expression as defined in the
documentation for expression)

(I don't mean to be nit-picky, I'm just trying to understand what's going on)

> So I would say your question should be:  "What's the best way to construct
> an expression vector s.t. evaluating its elements in order is like
> evaluating the body of a function?"
>
> And the answer to that is something like
>
> body2expr <- function(f) {
>  body <- body(f)
>  if (typeof(body) == "language" && identical(body[[1]], quote(`{`)))
> as.expression(as.list(body[-1]))
>  else as.expression(body)
> }

Ok, thanks.

Hadley

-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



More information about the R-devel mailing list