在R中应用两次函数

时间:2016-04-02 07:14:59

标签: r functional-programming

我想在R中定义一个函数,它将一个函数作为参数并将其两次应用于它的参数。

例如

x <- function twice (plusone 1)

3

In Haskell it is done by  twice f = \x -> f (f x)

如何在R?

中做到这一点

2 个答案:

答案 0 :(得分:7)

a

可以概括为

twice <- function(f, x) f(f(x))
twice(function(x) x+1, 1)
# 3

答案 1 :(得分:3)

如果您来自Haskell,您也会意识到在R中也很容易进行currying。这个答案也比@ baptiste更完整。见最后一句话

repeatf <-
  function (n) function (f) function (x)
    if (n<=0) x else repeatf (n-1) (f) (f(x))

once <- repeatf (1)
twice <- repeatf (2)
thrice <- repeatf (3)

square <- function (x) x * x
once (square) (2)    # 4
twice (square) (2)   # 16
thrice (square) (2)  # 256

值得注意的是,如果n是程序中的动态变量,则可能是0或负数。 repeatf仍会在这些情况下运作

repeatf (0) (square) (2)  # 2
repeatf (-3) (square) (2) # 2

@ baptiste的解决方案将失败

nice(square, 0, 2)   # Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
nice(square, -3, 2)  # Error: evaluation nested too deeply: infinite recursion / options(expressions=)?