Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
a local clone.

std.functional

Functions that manipulate other functions.

This module provides functions for compile time function composition. These
functions are helpful when constructing predicates for the algorithms in
std.algorithm or std.range.

Transforms a string representing an expression into a unary
function. The string must either use symbol name a as
the parameter or provide the symbol via the parmName argument.
If fun is not a string, unaryFun aliases itself away to fun.

Transforms a string representing an expression into a binary function. The
string must either use symbol names a and b as the parameters or
provide the symbols via the parm1Name and parm2Name arguments.
If fun is not a string, binaryFun aliases itself away to
fun.

int fun(int a, int b) { return a + b; }
alias fun5 = partial!(fun, 5);
writeln(fun5(6)); // 11
// Note that in most cases you'd use an alias instead of a value
// assignment. Using an alias allows you to partially evaluate template
// functions without committing to a particular type of the function.

template adjoin(F...) if (F.length == 1)

template adjoin(F...) if (F.length > 1)

Takes multiple functions and adjoins them together. The result is a
std.typecons.Tuple with one element per passed-in function. Upon
invocation, the returned tuple is the adjoined results of all
functions.

Note:
In the special case where only a single function is provided
(F.length == 1), adjoin simply aliases to the single passed function
(F[0]).

Pipes functions in sequence. Offers the same functionality as compose, but with functions specified in reverse order. This may
lead to more readable code in some situation because the order of
execution is the same as lexical order.

Example:

// Read an entire text file, split the resulting string in
// whitespace-separated tokens, and then convert each token into an
// integer
int[] a = pipe!(readText, split, map!(to!(int)))("file.txt");

Memoizes a function so as
to avoid repeated computation. The memoization structure is a hash table keyed by a
tuple of the function's arguments. There is a speed gain if the
function is repeatedly called with the same arguments and is more
expensive than a hash table lookup. For more information on memoization, refer to this book chapter.

Technically the memoized function should be pure because memoize assumes it will
always return the same result for a given tuple of arguments. However, memoize does not
enforce that because sometimes it
is useful to memoize an impure function, too.

Examples:

To memoize a recursive function, simply insert the memoized call in lieu of the plain recursive call.
For example, to transform the exponential-time Fibonacci implementation into a linear-time computation: