compose: Compose multiple functions together to create a new function

View source: R/adverb-compose.R

composeR Documentation

Compose multiple functions together to create a new function

Description

Create a new function that is the composition of multiple functions, i.e. compose(f, g) is equivalent to function(...) f(g(...)).

Usage

compose(..., .dir = c("backward", "forward"))

Arguments

...

Functions to apply in order (from right to left by default). Formulas are converted to functions in the usual way.

Dynamic dots are supported. In particular, if your functions are stored in a list, you can splice that in with ⁠!!!⁠.

.dir

If "backward" (the default), the functions are called in the reverse order, from right to left, as is conventional in mathematics. If "forward", they are called from left to right.

Value

A function

Adverbs

This function is called an adverb because it modifies the effect of a function (a verb). If you'd like to include a function created an adverb in a package, be sure to read faq-adverbs-export.

See Also

Other adverbs: auto_browse(), insistently(), negate(), partial(), possibly(), quietly(), safely(), slowly()

Examples

not_null <- compose(`!`, is.null)
not_null(4)
not_null(NULL)

add1 <- function(x) x + 1
compose(add1, add1)(8)

fn <- compose(\(x) paste(x, "foo"), \(x) paste(x, "bar"))
fn("input")

# Lists of functions can be spliced with !!!
fns <- list(
  function(x) paste(x, "foo"),
  \(x) paste(x, "bar")
)
fn <- compose(!!!fns)
fn("input")

purrr documentation built on Aug. 10, 2023, 9:08 a.m.