分配给R中%@%运算符的函数组合

分配给R中%@%运算符的函数组合,r,math,data-science,R,Math,Data Science,在数学中,我们经常使用函数的叠加。显然,我们可以定义任意数量函数的叠加,例如,(h∘G∘f) (x)(h)∘G∘f) (十)。我的问题是->如何定义叠加二元运算符%@% 让我们从一个简单的例子开始 sin%@%pi/4 上面的表达式返回值sin(−π/4) 评估时。我想得到一个%@%运算符的实现,它允许叠加任何有限数量的函数,如以下示例所示(请参见下文)。您能为我提供不需要任何额外R包的解决方案吗?这将非常有帮助 tanh%@%exp%@%abs%@%sin%@%pi/4以下函数将代码改编为类似

在数学中,我们经常使用函数的叠加。显然,我们可以定义任意数量函数的叠加,例如,(h∘G∘f) (x)(h)∘G∘f) (十)。我的问题是->如何定义叠加二元运算符%@%

让我们从一个简单的例子开始

sin%@%pi/4

上面的表达式返回值sin(−π/4) 评估时。我想得到一个%@%运算符的实现,它允许叠加任何有限数量的函数,如以下示例所示(请参见下文)。您能为我提供不需要任何额外R包的解决方案吗?这将非常有帮助


tanh%@%exp%@%abs%@%sin%@%pi/4

以下函数将代码改编为类似问题

`%@%` <- function(f, g) {
  if(is.function(g))
    function(...) f(g(...))
  else f(g)
}

sin %@% (-pi/4)
#[1] -0.7071068
(sin %@% cos)(-pi/4)
#[1] 0.6496369

我不知道这是否合适,但我的第一个意图是:

`%@%` <- function(f,g) {
  if(is.function(f) && is.function(g)) {
    #both functions, composition as usual
    return(function(...) {f(g(...))} )
  }
  if(!is.function(f)) {
    #f is no function, hence a constant value, return it.
    return(f)
  }
  if(is.function(f) && !is.function(g)) {
    #f is function, g not, hence g is the argumemnt to f
    return(f(g))
  }
}

`%@%`
`%@%` <- function(f,g) {
  if(is.function(f) && is.function(g)) {
    #both functions, composition as usual
    return(function(...) {f(g(...))} )
  }
  if(!is.function(f)) {
    #f is no function, hence a constant value, return it.
    return(f)
  }
  if(is.function(f) && !is.function(g)) {
    #f is function, g not, hence g is the argumemnt to f
    return(f(g))
  }
}

sq <- function(x) x^2
sq %@% sq %@% 5 #625
base::identity %@% base::identity %@% 5 #5
exp %@% log %@% 5 #5
5 %@% sin #5

tanh %@% exp %@% abs %@% sin %@% -pi/4 #0.1903985