I want to define a function in R that takes as argument a function and applies it twice to its arguments.
For example
x <- function twice (plusone 1)
3
In Haskell it is done by twice f = \x -> f (f x)
.
How to do that in R?
twice <- function(f, x) f(f(x))
twice(function(x) x+1, 1)
# 3
which may be generalised as
nice <- function(f, n, x) if(n==1) f(x) else Recall(f, n-1, f(x))
nice(function(x) x+1, 2, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With