在R中应用两次函数

Leo*_*kus 3 functional-programming r

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

例如

x <- function twice (plusone 1)

3

In Haskell it is done by  twice f = \x -> f (f x)
Run Code Online (Sandbox Code Playgroud)

.

如何在R中做到这一点?

bap*_*ste 7

twice <- function(f, x) f(f(x))
twice(function(x) x+1, 1)
# 3
Run Code Online (Sandbox Code Playgroud)

可以概括为

nice <- function(f, n, x) if(n==1) f(x) else Recall(f, n-1, f(x))    
nice(function(x) x+1, 2, 1)
Run Code Online (Sandbox Code Playgroud)