Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a function twice in R

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?

like image 517
Leon Backus Avatar asked Dec 28 '25 13:12

Leon Backus


1 Answers

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)
like image 122
baptiste Avatar answered Dec 31 '25 04:12

baptiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!