11

As a symptom of R being a functional language, it is possible to specify many control structures using pure functional notation. For example, an if statement:

> as.list((substitute(if(a == 1) 1 else 2)))
[[1]]
`if`

[[2]]
a == 1

[[3]]
[1] 1

[[4]]
[1] 2

> as.list(substitute(`if`(a == 1, 1, 2)))
[[1]]
`if`

[[2]]
a == 1

[[3]]
[1] 1

[[4]]
[1] 2

Out of curiosity I attempted to do the same for a function definition. Functions are typically constructed using the function(args) body syntax but there also exists a function named function in R. The problem I ran into is that the un-evaluated definition of a function will contain a pairlist:

> substitute(function(x = 1, a) {x + a})[[2]]
$x
[1] 1

$a
[empty symbol]

The second argument is a pairlist between the names of the arguments and there default values, which are possibly empty symbols. As far as I know, it is impossible to pass a list or a pairlist as part of expression using only manual calls. Below are my attempts:

> substitute(`function`(x, {x + 1}))
Error: badly formed function expression
> substitute(`function`((x), {x + 1}))
function(`(`, x) {
    x + 1
}

If I pass a single symbol as the second argument to `function`, an error is thrown (and this wouldn't work for a function with multiple arguments). When passing a call as the second argument, the call appears to be coerced to a list upon being parsed.

This can be abused by using the first argument as the name of the call:

> substitute(`function`(a(x), {x + 1}))
function(a, x) {
     x + 1
}

However, the call is not actually converted to a pairlist and only appears to be so. When evaluating this expression, an error is thrown. It would be ideal to somehow insert a list / pairlist into the result of a call to substitute. Does anyone know how to do so?

Jon Claus
  • 2,862
  • 4
  • 22
  • 33
  • 4
    Is [this](http://stackoverflow.com/q/12982528/324364) question helpful at all? – joran Jun 04 '14 at 17:10
  • I was hoping to directly use the primitive function `\`function\`` as I believe this is what R evaluates when constructing a funcion. – Jon Claus Jun 04 '14 at 17:33
  • 1
    Look at `make_function4` in the answer I linked to, I think that's the version you're referring to. – joran Jun 04 '14 at 17:36
  • 1
    You may find the chapter at http://adv-r.had.co.nz/Functions.html useful. – Brian Diggs Jun 05 '14 at 14:27
  • no idea what your goal is but I'd start thinking about proper class definitions. I think your control structures could just be methods. – miles2know Oct 17 '14 at 05:20

1 Answers1

1

This will not be prompt answer but I just tried to focus on your function call.

Just try this code:

   as.list((substitute(function(x = 1, a) {x + a})))
   [[1]]

    `function`

  [[2]]

  [[2]]$x

  [1] 1

  [[2]]$a

  [[3]]
   {
      x + a
    }
 [[4]]
      function(x = 1, a) {x + a}
Leeya
  • 170
  • 2
  • 15