curry: Curry a function

View source: R/curry.R

curryR Documentation

Curry a function

Description

curry() curries functions—it reconstitutes a function as a succession of single-argument functions. For example, curry() produces the the function

function(x) {
  function(y) {
    function(z) {
      x * y * z
    }
  }
}

from the function function(x, y, z) x * y * z.

curry_fn() produces a curried function from an fn()-style function declaration, which supports quasiquotation of a function’s body and (default) argument values.

Usage

curry(f, env = environment(f))

curry_fn(..., ..env = parent.frame())

Arguments

f

Function.

env

Environment of the curried function or NULL. If NULL, the environment of the curried function is the calling environment.

...

Function declaration, which supports quasiquotation.

..env

Environment in which to create the function (i.e., the function’s enclosing environment).

Details

Dots (...) are treated as a unit when currying. For example, curry() transforms function(x, ...) list(x, ...) to function(x) { function(...) list(x, ...) }.

Value

A function of nested single-argument functions.

See Also

fn()

Examples

curry(function(x, y, z = 0) x + y + z)
double <- curry(`*`)(2)
double(3)  # 6

curry_fn(x, y, z = 0 ~ x + y + z)
curry_fn(target, ... ~ identical(target, ...))

## Delay unquoting to embed argument values into the innermost function
compare_to <- curry_fn(target, x ~ identical(x, QUQ(target)))
is_this <- compare_to("this")
is_this("that")  # FALSE
is_this("this")  # TRUE
classify_as <- curry_fn(class, x ~ `class<-`(x, QUQ(class)))
as_this <- classify_as("this")
as_this("Some object")  # String of class "this"


egnha/nofrills documentation built on March 23, 2022, 9:03 p.m.