在R中手动构造函数

时间:2021-12-30 18:15:33

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:

作为R是函数式语言的症状,可以使用纯函数符号指定许多控制结构。例如,if语句:

> 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:

出于好奇,我试图对函数定义做同样的事情。函数通常使用函数(args)body语法构造,但在R中也存在一个名为function的函数。我遇到的问题是函数的未评估定义将包含一个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:

第二个参数是参数名称和默认值之间的一个pairlist,它们可能是空符号。据我所知,仅使用手动调用就不可能将列表或pairlist作为表达式的一部分传递。以下是我的尝试:

> 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.

如果我将单个符号作为第二个参数传递给`function`,则会抛出一个错误(这对于具有多个参数的函数不起作用)。当将调用作为第二个参数传递时,调用似乎在被解析时被强制转换为列表。

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?

但是,呼叫实际上并没有转换成一个轮滑,只是看起来如此。在计算此表达式时,会引发错误。以某种方式将列表/ pairlist插入到替换调用的结果中是理想的。有谁知道怎么做?

1 个解决方案

#1


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}

#1


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}