combinators

Methods

(static) apply(f, x) → {*}

Source:

Applies a function.

This is an implementation of the I* combinator. It basically is just Function.apply with null as a target and only a single argument.

const inc = add(1)
const result = apply(inc, 4)

console.log(result) // 5

This function is provided primarily for completeness. Even if direct function calls aren't possible, apply and call do the same thing with additional options.

Parameters:
Name Type Description
f function

A single-argument function to apply to x.

x *

The argument to be applied to f.

Returns:

The value that f returns when applied to x.

Type
*

(static) applyTo(x, f) → {*}

Source:

Applies a function to an argument in reverse order.

This is an implementation of the T combinator. This is one of the rare combinators that's at least sometimes referred to by its bird name; in this case, thrush is a function that can be found in Scheme and also in some Haskell libraries.

const inc = add(1)
const result = applyTo(4, inc)

console.log(result) // 5
Parameters:
Name Type Description
x *

The argument to be applied to f.

f function

A single-argument function to apply to x.

Returns:

The value that f returns when applied to x.

Type
*

(static) compose(f, g, x)

Source:

Composes two functions.

This is a direct implementation of the B combinator, composing two single-argument functions.

Composition is perhaps the most basic operation of functional programming (after function application). It is widely used in many, many languages. Its Haskell equivalent is ., its APL equivalent is ∘ (which is the mathematical symbol for composition), and stack-based languages make composition so basic as to do it by literally putting two functions next to each other in the code.

Composing traditionally happens in right-to-left order (function g will be applied to value x, and then function f is applied to that result). For left-to-right order, use pipe instead.

// Turns the digits in an array into strings and then concatenates them
const stringify = compose (reduce (add)) (map (string))
const result = stringify ([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
console.log(result)   // "31415926535"
Parameters:
Name Type Description
f function

The second function executed, applied to the result of g's application of x. The result of this function will be compose's return value.

g function

The first function executed, applied to x. Its result becomes the argument to f.

x *

The argument that is passed to g.

Returns:

Function f's result when applied to the result of g being applied to x.

(static) composev(…fns) → {function}

Source:

Combines two or more single-parameter functions into one single-parameter function that passes the results from its contained functions to the next and returns the result of the last contained function.

This is an implementation of the B combinator except that it can compose more than two functions. It is the equivalent of chaining compose an arbitrary number of times.

The order of the functions is reversed, as is traditional in functional programming. If you need the order to not be reversed, use pipeAll.

This function, being variadic, is not curried. However, the result is a single-argument function, so it can be used in any library function.

Parameters:
Name Type Attributes Description
fns function <repeatable>

The functions that should be composed into a single function.

Returns:

A single function that is the composition of all of the provided functions.

Type
function

(static) constant(x) → {function}

Source:

Creates a constant function, which always returns the same value no matter its arguments.

This is an implementation of the K combinator. Its useful in contexts where a function is required but you don't care about the argument(s) to that function.

const fn = constant(1729)

console.log(fn())       // 1729
console.log(fn('test')) // 1729
console.log(fn(1728))   // 1729
Parameters:
Name Type Description
x *

The value that the constant function should return.

Returns:

A function that returns x when invoked no matter the arguments.

Type
function

(static) converge(f, g, h, x) → {*}

Source:

Applies two different functions to an argument, and then applies a third function to the two results.

This is an implementation of the S' combinator. It's also equivalent to a monadic fork in array languages such as APL and J. It's a very handy combinator for pre-processing an argument before passing it to a main function.

This combinator is similar to substitute. In fact, passing in identity as either g or h will make it behave identically to substitute. It's similar to the famous liftA2 in Haskell.

This first example creates a function average that passes its argument (an array of numbers) to a a summing function and to a counting function before using a division function on the results. In other words, it sums the elements of an array and then divides by the number of elements in that array, which is just calculating the average.

const sum = reduce (add)
const length = prop ('length')
const average = converge (div) (sum) (length)

const avg1 = average ([1, 2, 3, 4, 5])
const avg2 = average ([10, 2, 6, 4, 8])

console.log(avg1) // 3
console.log(avg2) // 6

This second example is a famous one from array languages: determining whether a string is a palindrome. (It's famous in array languages because something so "complex" can be done in five characters in APL: (⌽≡⊢). This is a fork in APL, which is reproduced by converge.) This is done by reversing the string and comparing that to the original (unreversed) string. It shows a case where identity is used as one of the initial functions and how that can be replaced with substitute.

const isPalindrome = converge (eq) (compose (collect) (reverse)) (identity)
// This can be done more compactly with `substitute` since one of the
// functions is `identity`:
// const isPalindrome = substitute (eq) (compose (collect) (reverse))

const radar = isPalindrome('radar')
const test = isPalindrome('test')

console.log(radar) // true
console.log(test)  // false
Parameters:
Name Type Description
f function

A function of two parameters. It's applied to the return values of g and h when each is applied to x.

g function

A function of one parameter. It's applied to x and the return value is passed to f.

h function

A function of one parameter. It's applied to x and the return value is passed to f.

x *

A value that is passed to functions g and h separately.

Returns:

The return value of function f.

Type
*

(static) dup(f, x) → {*}

Source:

Applies a function to an argument twice, effectively duplicating the argument.

This is an implementation of the W combinator.

const square = dup (mul)
const s2 = square (2)
const s5 = square (5)

console.log(s2) // 4
console.log(s5) // 25
Parameters:
Name Type Description
f function

A function that gets applied to x twice.

x *

An argument that is passed to f twice.

Returns:

The return value of f when applied to x twice.

Type
*

(static) fix(f) → {function}

Source:

Produces a function that is a fixed point of a supplied function.

A fixed point is a value that is mapped to itself by a function. Since this function provides a fixed point, that means

fix(f) = f(fix(f))

for any function f that has a fixed point.

The standard demonstration for a fixed point of a function is mimicking recursion without actually using recursion. This has little practical value in JavaScript because there already are recursive functions, but it's interesting to see how recursion could be modeled in a language that doesn't allow recursion (which can happen if a language does not have named functions).

// The normal way, with a recursive function
const fact = x => (x === 0 ? 1 : x * fact(x - 1))

// The fixed point way
// This function replaces the recursive call with a call to a function that is passed in
const fn = f => x => (x === 0 ? 1 : x * f(x - 1))
const fixFact = fix(fn)

const fact5 = fact(5)
const fixFact5 = fixFact(5)

console.log(fact5)    // 120
console.log(fixFact5) // 120
Parameters:
Name Type Description
f function

A function to return the fixed point function for.

Returns:

A new function that is the fixed point of function f.

Type
function

(static) identity(x) → {*}

Source:

The identity function. This simply returns the argument given to it.

That makes it an implementation (trival as it is) of the I combinator. It's most often used for contexts where you need to use a function but you instead have a value. identity is a function, but it gives you that value.

// Here's a reasonable example: a palindrome detector. In this case we want to see if a
// value is equal to its reverse.

// converge passes the results of its second and third functions to its first function.
// Since we want to pass the original string as one of the arguments to eq, but converge
// requires a function instead of a simple value, we use identity as a function that
// provides that value.

const isPalindrome = converge(eq, identity, compose(reduce(add), reverse))
Parameters:
Name Type Description
x *

The value to be returned.

Returns:

The argument x.

Type
*

(static) on(f, g, x, y) → {*}

Source:

Applies a function to a pair of arguments separately, then applies another function to the two results.

This is an implementation of the P (also known as Ψ) combinator. It's similar to converge, except that this function applies one funciton to two different arguments, while converge applies two different functions each to one argument.

A common use for this combinator uses g to retrieve (from an object property or a database, for example) or to preprocess values before performing a calculation with f.

const getLen = prop ('length')
const compare = (a, b) => a < b ? 'second' : 'first'
const longest = on (compare) (getLen)

const ex1 = longest ([1, 2, 3]) ([1, 2, 3, 4])
const ex2 = longest ([1, 2, 3]) ([1, 2])

console.log(ex1) // "second"
console.log(ex2) // "first"
Parameters:
Name Type Description
f function

A two-argument function that is applied to the return values of g.

g function

A single-argment function that is applied to both arguments.

x *

The first argument that is passed to g.

y *

The second argument that is passed to g.

Returns:

The return value of f when applied to the results of g when applied to arguments x and y.

Type
*

(static) pipe(f, g)

Source:

Composes two functions in left-to-right order.

This is the same as compose except for the left-to-right order replacing compose's right-to-left order. That makes it an implementation of the **Q combinator, or alternately, the same as swap (compose).

This is then similar to Clojure's ->> threading macro.

// Same as example in `compose`, for contrast
// Turns the digits in an array into strings and then concatenates them
const stringify = pipe (map (string)) (reduce (add))
const result = stringify ([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
console.log(result)   // "31415926535"
Parameters:
Name Type Description
f function

The first function executed, applied to x. Its result becomes the argument to g.

g function

The second function executed, applied to the result of f's application of x. The result of this function will be compose's return value.

Returns:

Function g's result when applied to the result of f being applied to x.

(static) pipev(…fns) → {function}

Source:

Combines two or more single-parameter functions into one single-parameter function that passes the results from its contained functions to the next and returns the result of the last contained function.

This is an implementation of the B combinator except that the order of the composed functions is reversed and that it can All more than two functions. (In the case of three or more, it's the same as using the B combinator multiple times.)

The order of the functions is not reversed. The first function listed is the first applied. This is contrary to the order most often used in functional programming (and opposite of the order in composeAll), but there are times when the piped order makes more sense than the composed order.

This function, being variadic, is not curried. However, the result is a single-argument function, so it can be used in any library function.

Parameters:
Name Type Attributes Description
fns function <repeatable>

The functions that should be composed into a single function.

Returns:

A single function that is the composition of all of the provided functions, but with the order of execution reversed.

Type
function

(static) rotl(fn, x, y, z) → {function}

Source:

Rotates a three-parameter function's arguments so that the first parameter is applied last.

To rotate the arguments in the other direction, use rotr.

This is an implementation of the R* combinator. It takes its name from Factor's rot function; Factor's function to rotate in the opposite direction is -rot and we can't use a - in a function name in JavaScript, so we use rotl and rotr instead.

rotl makes the first argument given into the last argument applied. This is very useful for functions that take their data as their first argument; it can turn them into functions which take their data as their last argument, which is in many cases easier to compose.

const sub3 = (x, y, z) => x - y - z

const result = rotl (sub3) (1) (5) (-2) // equivalent of sub3 (5) (-2) (1)

console.log(result)  // 6
Parameters:
Name Type Description
fn function

A function of three arguments.

x *

The first argument, which fn will apply as its third argument.

y *

The second argument, which fn will apply as its first argument.

z *

The third argument, which fn will apply as its second argument.

Returns:

A curried function which expects its arguments in left-rotated order from fn but otherwise behaves the same.

Type
function

(static) rotr(fn, x, y, z) → {function}

Source:

Rotates a three-parameter function's arguments so that the last parameter is applied first.

To rotate the arguments in the other direction, use rotl.

This is an implementation of BR*R*, or applying R* twice to result in the opposite rotation from R* itself. It takes its name from Factor's rot function; Factor's actual function to rotate arguments in this direction is -rot and we can't use a - in a function name in JavaScript, so we use rotl and rotr instead.

rotr turns the last argument given into the first argument applied. This is in particular useful in conjunction with the cond operator, where often the true and false (second and third) arguments are partially applied and you want to leave the conditional (the first argument) as the last argument.

const sub3 = (x, y, z) => x - y - z

const result = rotl (sub3) (1) (5) (-2) // equivalent of sub3 (-2) (1) (5)

console.log(result)  // -8
Parameters:
Name Type Description
fn function

A function of three arguments.

x *

The first argument, which fn will apply as its second argument.

y *

The second argument, which fn will apply as its third argument.

z *

The third argument, which fn will apply as its first argument.

Returns:

A curried function which expects its arguments in right-rotated order from fn but otherwise behaves the same.

Type
function

(static) substitute(f, g, x) → {*}

Source:

Executes a binary function, applying it to an argument and to the result of passing that argument to a unary function.

This is an implementation of the S combinator which drops the requirement that f be a curried function (it can be, but it doesn't have to be). The name "substitute" comes from the idea that rather than applying the first function to a value twice, it's applied to that value and a substitution of that value generated by the second function. This is a little thin in justification, but calling this operation "substitution" does have the weight of history behind it.

This is a hook in J. It is also a monadic fork in J, BQN, or APL, but only if the left outer function is identity (or the right outer function, if the middle function is commutative).

substitute itself is a function that can be used partially if so desired, as in this example.

// This is a point-free equivalent of:
// const lastIndex = array => array.length - 1
// const lastElement = array => array[lastIndex(array)]

const lastIndex = compose (swap (sub) (1)) (prop ('length'))
const lastElement = substitute (propOf) (lastIndex)

const result = lastElement([1, 2, 3, 4, 5])
console.log(result)  // 5
Parameters:
Name Type Description
f function

A function of two parameters. It is applied to x and to the result of g's application to x.

g function

A function of one parameter. It is applied to x and the result given to f as its second argument.

x *

A value that becomes the first argument to f and the sole argument to g.

Returns:

The result of f when applied to x and the result of g.

Type
*

(static) swap(fn, x, y) → {function}

Source:

Flips the order of the arguments on a two-argument function.

This is an implementation of the C combinator that dispenses with the requirement that its function argument is a curried function. swap will work with both. The result, either way, is a curried function with the argument order reversed.

swap itself comes pre-curried so it's easy to generate a unary function out of a binary function with its second argument applied instead of its first.

This function is called flip in Haskell, but swap is the name of the same function in Factor. Since many of the other argument-shuffing functions also come from Factor, I have retained that here.

const sub = (x, y) => x - y

const result = swap(sub)(1)(5)  // equivalent to sub(5)(1)

console.log(result)  // 4
Parameters:
Name Type Description
fn function

A function of two arguments.

x *

The first argument, which fn will apply as its second argument.

y *

The second argument, which fn will apply as its first argument.

Returns:

A curried function which expects its arguments in reverse order from fn but otherwise behaves the same.

Type
function