Home > Enterprise >  How to nest a list of functions?
How to nest a list of functions?

Time:04-17

I have a list of functions.

fn=list(
  function(x) { ... }
  , function(x) { ... }
  , ...
)

I want to generate a nested function of these functions.

fn[[1]](fn[[2]](fn[[3]](...(fn[[m]](x))))) # Suppose there are m functions in the list.

Is there an easy way to composite these individual function as a nested function?

CodePudding user response:

Another Base R approach:

fun <- function(x) Reduce(function(y, f)f(y), fn, init = x)
fun(1:10)
 [1]  3  4  5  6  7  8  9 10 11 12

CodePudding user response:

With purrr::compose you could do:

fn <- list(function(x) x^2, sqrt, function(x) x   2)

fn_compose <- purrr::compose(!!!fn)

fn_compose(c(1:10))
#>  [1]  3  4  5  6  7  8  9 10 11 12

CodePudding user response:

In base R, use the accepted answer to this question.

composite <- function(f,g) function(...) f(g(...))
fn <- list(function(x) x^2, sqrt, function(x) x   2)
f <- Reduce(composite, fn)

f(1:10)
#>  [1]  3  4  5  6  7  8  9 10 11 12

Created on 2022-04-17 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related