From peter.meilstrup at gmail.com  Thu Oct  4 00:05:53 2012
From: peter.meilstrup at gmail.com (Peter Meilstrup)
Date: Wed, 3 Oct 2012 15:05:53 -0700
Subject: [Rd] Creating functions programmatically
In-Reply-To: <CABdHhvGhFHTVUvCY_n9_VaxyEZ8+P7rZjZMh9wqQQZyDmQZSAA@mail.gmail.com>
References: <CABdHhvH9Q3L16aCQPg=Tn5N+GqJTDW2vhf3=y6_DYcUOXwYvmQ@mail.gmail.com>
	<506C4B1F.3070403@gmail.com>
	<CABdHhvGhFHTVUvCY_n9_VaxyEZ8+P7rZjZMh9wqQQZyDmQZSAA@mail.gmail.com>
Message-ID: <CAJoaRhagfQPR4F9DTQH6yR-8KW1bJ0GVhb5dEGsYoLq38xVhTw@mail.gmail.com>

On Wed, Oct 3, 2012 at 7:47 AM, Hadley Wickham <h.wickham at gmail.com> wrote:
>> There is:  it is `function`.  The parser converts your function definitions
>> into a call to it.  (It has 3 arguments: the formals, the body, and the
>> srcref.  The environment is added when it is evaluated.)
>>
>> So your make_function below is pretty similar (but because `function` is
>> primitive, some of the evaluation rules might be different).
>
> Hmm, I thought I had it working, but now I can't figure out the
> arguments to `function`:
>
>> `function`(NULL,NULL)
> function ()
> NULL
>
>> `function`(alist(a = 1), NULL)
> Error: invalid formal argument list for "function"
>
> I'm obviously missing something dumb.

I think `function` does not eval its arguments, and it demands a
pairlist. So this works:

f <- eval(substitute(`function`(args, body),
list(args=as.pairlist(alist(a=1)), body=quote(a+1))))

The other thing to notice is a syntax difference between function and
ordinary calls: when writing

function(b=default, a) {}

"a" is interpreted as a name rather than value; to programatically get
the same effect you'd have to use

alist(b=default, a= )

Peter



[Rd] Creating functions programmatically
Peter Meilstrup