Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.111.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
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 usinga local clone.

std.functional

Functions that manipulate other functions.
This module provides functions for compile time function composition. Thesefunctions are helpful when constructing predicates for the algorithms instd.algorithm orstd.range.
Function NameDescription
adjoinJoins a couple of functions into one that executes the original functions independently and returns a tuple with all the results.
compose,pipeJoin a couple of functions into one that executes the original functions one after the other, using one function's result for the next function's argument.
lessThan,greaterThan,equalToReady-made predicate functions to compare two values.
memoizeCreates a function that caches its result for fast re-evaluation.
notCreates a function that negates another.
partialCreates a function that binds the first argument of a given function to a given value.
curryConverts a multi-argument function into a series of single-argument functions. f(x, y) == curry(f)(x)(y)
reverseArgsPredicate that reverses the order of its arguments.
toDelegateConverts a callable to a delegate.
unaryFun,binaryFunCreate a unary or binary function from a string. Most often used when defining algorithms on ranges.
bindPasses the fields of a struct as arguments to a function.
ctEvalEnforces the evaluation of an expression during compile-time.
License:
Boost License 1.0.
Authors:
Andrei Alexandrescu

Sourcestd/functional.d

templateunaryFun(alias fun, string parmName = "a")
Transforms astring representing an expression into a unaryfunction. Thestring must either use symbol namea asthe parameter or provide the symbol via theparmName argument.
Parameters:
funastring or a callable
parmNamethe name of the parameter iffun is a string. Defaults to"a".
Returns:
Iffun is astring, a new single parameter function
Iffun is not astring, an alias tofun.
Examples:
// Strings are compiled into functions:alias isEven =unaryFun!("(a & 1) == 0");assert(isEven(2) && !isEven(1));
templatebinaryFun(alias fun, string parm1Name = "a", string parm2Name = "b")
Transforms astring representing an expression into a binary function. Thestring must either use symbol namesa andb as the parameters orprovide the symbols via theparm1Name andparm2Name arguments.
Parameters:
funastring or a callable
parm1Namethe name of the first parameter iffun is a string. Defaults to"a".
parm2Namethe name of the second parameter iffun is a string. Defaults to"b".
Returns:
Iffun is not a string,binaryFun aliases itself away tofun.
Examples:
alias less =binaryFun!("a < b");assert(less(1, 2) && !less(2, 1));alias greater =binaryFun!("a > b");assert(!greater("1","2") && greater("2","1"));
aliaslessThan = safeOp!"<".safeOp(T0, T1)(auto ref T0 a, auto ref T1 b);
Predicate that returnsa < b. Correctly compares signed and unsigned integers, ie. -1 < 2U.
Examples:
assert(lessThan(2, 3));assert(lessThan(2U, 3U));assert(lessThan(2, 3.0));assert(lessThan(-2, 3U));assert(lessThan(2, 3U));assert(!lessThan(3U, -2));assert(!lessThan(3U, 2));assert(!lessThan(0, 0));assert(!lessThan(0U, 0));assert(!lessThan(0, 0U));
aliasgreaterThan = safeOp!">".safeOp(T0, T1)(auto ref T0 a, auto ref T1 b);
Predicate that returnsa > b. Correctly compares signed and unsigned integers, ie. 2U > -1.
Examples:
assert(!greaterThan(2, 3));assert(!greaterThan(2U, 3U));assert(!greaterThan(2, 3.0));assert(!greaterThan(-2, 3U));assert(!greaterThan(2, 3U));assert(greaterThan(3U, -2));assert(greaterThan(3U, 2));assert(!greaterThan(0, 0));assert(!greaterThan(0U, 0));assert(!greaterThan(0, 0U));
aliasequalTo = safeOp!"==".safeOp(T0, T1)(auto ref T0 a, auto ref T1 b);
Predicate that returnsa == b. Correctly compares signed and unsigned integers, ie. !(-1 == ~0U).
Examples:
assert(equalTo(0U, 0));assert(equalTo(0, 0U));assert(!equalTo(-1, ~0U));
templatereverseArgs(alias pred)
N-ary predicate that reverses the order of arguments, e.g., givenpred(a, b, c), returnspred(c, b, a).
Parameters:
predA callable
Returns:
A function which callspred after reversing the given parameters
Examples:
alias gt =reverseArgs!(binaryFun!("a < b"));assert(gt(2, 1) && !gt(1, 1));
Examples:
int x = 42;bool xyz(int a,int b) {return a * x < b / x; }auto foo = &xyz;foo(4, 5);alias zyx =reverseArgs!(foo);writeln(zyx(5, 4));// foo(4, 5)
Examples:
alias gt =reverseArgs!(binaryFun!("a < b"));assert(gt(2, 1) && !gt(1, 1));int x = 42;bool xyz(int a,int b) {return a * x < b / x; }auto foo = &xyz;foo(4, 5);alias zyx =reverseArgs!(foo);writeln(zyx(5, 4));// foo(4, 5)
Examples:
int abc(int a,int b,int c) {return a * b + c; }alias cba =reverseArgs!abc;writeln(abc(91, 17, 32));// cba(32, 17, 91)
Examples:
int a(int a) {return a * 2; }alias _a =reverseArgs!a;writeln(a(2));// _a(2)
Examples:
int b() {return 4; }alias _b =reverseArgs!b;writeln(b());// _b()
templatenot(alias pred)
Negates predicatepred.
Parameters:
predA string or a callable
Returns:
A function which callspred and returns the logical negation of its return value.
Examples:
import std.algorithm.searching : find;import std.uni : isWhite;string a ="   Hello, world!";writeln(find!(not!isWhite)(a));// "Hello, world!"
templatepartial(alias fun, alias arg)
Partiallyappliesfun by tying its first argument toarg.
Parameters:
funA callable
argThe first argument to apply tofun
Returns:
A new function which callsfun witharg plus the passed parameters.
Examples:
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.
Examples:
// Overloads are resolved when the partially applied function is called// with the remaining arguments.struct S{staticchar fun(int i, string s) {return s[i]; }staticint fun(int a,int b) {return a * b; }}alias fun3 =partial!(S.fun, 3);writeln(fun3("hello"));// 'l'writeln(fun3(10));// 30
autocurry(alias F)()
if (isCallable!F && Parameters!F.length);

autocurry(T)(Tt)
if (isCallable!T && Parameters!T.length);
Takes a function of (potentially) many arguments, and returns a function takingone argument and returns a callable taking the rest. f(x, y) == curry(f)(x)(y)
Parameters:
Fa function taking at least one argument
Tta callable object whose opCall takes at least 1 object
Returns:
A single parameter callable object
Examples:
int f(int x,int y,int z){return x + y + z;}auto cf =curry!f;auto cf1 = cf(1);auto cf2 = cf(2);writeln(cf1(2)(3));// f(1, 2, 3)writeln(cf2(2)(3));// f(2, 2, 3)
Examples:
//works with callable structs toostruct S{int w;int opCall(int x,int y,int z)    {return w + x + y + z;    }}S s;s.w = 5;auto cs =curry(s);auto cs1 = cs(1);auto cs2 = cs(2);writeln(cs1(2)(3));// s(1, 2, 3)writeln(cs1(2)(3));// (1 + 2 + 3 + 5)writeln(cs2(2)(3));// s(2, 2, 3)
templateadjoin(F...) if (F.length >= 1)
Takes multiple functions and adjoins them together.
Parameters:
Fthe call-able(s) to adjoin
Returns:
A new function which returns astd.typecons.Tuple. Each of the elements of the tuple will be the return values ofF.

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

Examples:
import std.typecons : Tuple;staticbool f1(int a) {return a != 0; }staticint f2(int a) {return a / 2; }auto x =adjoin!(f1, f2)(5);assert(is(typeof(x) == Tuple!(bool,int)));assert(x[0] ==true && x[1] == 2);
templatecompose(fun...) if (fun.length > 0)
Composes passed-in functionsfun[0], fun[1], ....
Parameters:
funthe call-able(s) orstring(s) to compose into one function
Returns:
A new functionf(x) that in turn returnsfun[0](fun[1](...(x)))....
See Also:
Examples:
import std.algorithm.comparison : equal;import std.algorithm.iteration : map;import std.array : split;import std.conv : to;// First split a string in whitespace-separated tokens and then// convert each token into an integerassert(compose!(map!(to!(int)), split)("1 2 3").equal([1, 2, 3]));
templatepipe(fun...)
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.
Parameters:
funthe call-able(s) orstring(s) to compose into one function
Returns:
A new functionf(x) that in turn returnsfun[$-1](...fun[1](fun[0](x)))....

Example

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

See Also:
Examples:
import std.conv : to;string foo(int a) {return to!(string)(a); }int bar(string a) {return to!(int)(a) + 1; }double baz(int a) {return a + 0.5; }writeln(compose!(baz, bar, foo)(1));// 2.5writeln(pipe!(foo, bar, baz)(1));// 2.5writeln(compose!(baz,`to!(int)(a) + 1`, foo)(1));// 2.5writeln(compose!(baz, bar)("1"[]));// 2.5writeln(compose!(baz, bar)("1"));// 2.5writeln(compose!(`a + 0.5`,`to!(int)(a) + 1`, foo)(1));// 2.5
templatememoize(alias fun)

templatememoize(alias fun, uint maxSize)
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 tothis book chapter.

Example

double transmogrify(int a, string b){   ... expensive computation ...}alias fastTransmogrify =memoize!transmogrify;unittest{auto slow = transmogrify(2,"hello");auto fast = fastTransmogrify(2,"hello");assert(slow == fast);}

Parameters:
funthe call-able to memozie
maxSizeThe maximum size of the GC buffer to hold the return values
Returns:
A new function which callsfun and caches its return values.

NoteTechnically the memoized function should be pure becausememoize 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:
ulong fib(ulong n) @safenothrow{return n < 2 ? n :memoize!fib(n - 2) +memoize!fib(n - 1);}writeln(fib(10));// 55
Examples:
To improve the speed of the factorial function,
ulong fact(ulong n) @safe{return n < 2 ? 1 : n *memoize!fact(n - 1);}writeln(fact(10));// 3628800
Examples:
This memoizes all values offact up to the largest argument. To only cache the final result, movememoize outside the function as shown below.
ulong factImpl(ulong n) @safe{return n < 2 ? 1 : n * factImpl(n - 1);}alias fact =memoize!factImpl;writeln(fact(10));// 3628800
Examples:
When themaxSize parameter is specified, memoize will used a fixed size hash table to limit the number of cached entries.
ulong fact(ulong n){// Memoize no more than 8 valuesreturn n < 2 ? 1 : n *memoize!(fact, 8)(n - 1);}writeln(fact(8));// 40320// using more entries than maxSize will overwrite existing entrieswriteln(fact(10));// 3628800
autotoDelegate(F)(auto ref Ffp)
if (isCallable!F);
Convert a callable to a delegate with the same parameter list and return type, avoiding heap allocations and use of auxiliary storage.
Parameters:
Ffpa function pointer or an aggregate type withopCall defined.
Returns:
A delegate with the context pointer pointing to nothing.

Example

void doStuff() {    writeln("Hello, world.");}void runDelegate(voiddelegate() myDelegate) {    myDelegate();}auto delegateToPass =toDelegate(&doStuff);runDelegate(delegateToPass);// Calls doStuff, prints "Hello, world."

Bugs:
  • Does not work with@safe functions.
  • Ignores C-style / D-style variadic arguments.
Examples:
staticint inc(refuint num) {    num++;return 8675309;}uint myNum = 0;auto incMyNumDel =toDelegate(&inc);auto returnVal = incMyNumDel(myNum);writeln(myNum);// 1
templatebind(alias fun)
Passes the fields of a struct as arguments to a function.
Can be used with a function literal to give temporary names to the fields of a struct or tuple.
Parameters:
funCallable that the struct's fields will be passed to.
Returns:
A function that accepts a single struct as an argument and passes its fields tofun when called.
Examples:
Giving names to tuple elements
import std.typecons : tuple;auto name = tuple("John","Doe");string full = name.bind!((first, last) => first ~" " ~ last);writeln(full);// "John Doe"
Examples:
Passing struct fields to a function
import std.algorithm.comparison : min, max;struct Pair{int a;int b;}auto p = Pair(123, 456);assert(p.bind!min == 123);// min(p.a, p.b)assert(p.bind!max == 456);// max(p.a, p.b)
Examples:
In a range pipeline
import std.algorithm.iteration : map, filter;import std.algorithm.comparison : equal;import std.typecons : tuple;auto ages = [    tuple("Alice", 35),    tuple("Bob",   64),    tuple("Carol", 21),    tuple("David", 39),    tuple("Eve",   50)];auto overForty = ages    .filter!(bind!((name, age) => age > 40))    .map!(bind!((name, age) => name));assert(overForty.equal(["Bob","Eve"]));
ref autobind(T)(auto ref Targs)
if (is(T == struct));
Parameters:
TargsThe struct or tuple whose fields will be used as arguments.
Returns:
fun(args.tupleof)
enum autoctEval(alias expr);
Enforces the evaluation of an expression during compile-time.
Computes the value of an expression during compilation (CTFE).
This is useful for call chains in functional programming where declaring anenum constant would require splitting the pipeline.
Parameters:
exprexpression to evaluate
See Also:
Examples:
import std.math : abs;// No explicit `enum` needed.float result =ctEval!(abs(-3));writeln(result);// 3// Can be statically asserted.staticassert(ctEval!(abs(-4)) == 4);staticassert(ctEval!(abs( 9)) == 9);
Examples:
import core.stdc.math : round;import std.conv : to;import std.math : abs, PI, sin;// `round` from the C standard library cannot be interpreted at compile// time, because it has no available source code. However the function// calls preceding `round` can be evaluated during compile time.int result =ctEval!(abs(sin(1.0)) * 180 / PI)    .round()    .to!int();writeln(result);// 48
Copyright © 1999-2025 by theD Language Foundation | Page generated byDdoc on Fri Oct 10 22:10:07 2025

[8]ページ先頭

©2009-2025 Movatter.jp