Merge pull request #5970 from wilzbach/markdownify-algorithm

Markdownify std.algorithm
merged-on-behalf-of: Jack Stouffer <jack@jackstouffer.com>
This commit is contained in:
The Dlang Bot 2018-01-03 15:44:56 +01:00 committed by GitHub
commit db2d2413b4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 652 additions and 660 deletions

View file

@ -8,41 +8,41 @@ $(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description)) $(TR $(TH Function Name) $(TH Description))
$(T2 among, $(T2 among,
Checks if a value is among a set of values, e.g. Checks if a value is among a set of values, e.g.
$(D if (v.among(1, 2, 3)) // `v` is 1, 2 or 3)) `if (v.among(1, 2, 3)) // `v` is 1, 2 or 3`)
$(T2 castSwitch, $(T2 castSwitch,
$(D (new A()).castSwitch((A a)=>1,(B b)=>2)) returns $(D 1).) `(new A()).castSwitch((A a)=>1,(B b)=>2)` returns `1`.)
$(T2 clamp, $(T2 clamp,
$(D clamp(1, 3, 6)) returns $(D 3). $(D clamp(4, 3, 6)) returns $(D 4).) `clamp(1, 3, 6)` returns `3`. `clamp(4, 3, 6)` returns `4`.)
$(T2 cmp, $(T2 cmp,
$(D cmp("abc", "abcd")) is $(D -1), $(D cmp("abc", "aba")) is $(D 1), `cmp("abc", "abcd")` is `-1`, `cmp("abc", "aba")` is `1`,
and $(D cmp("abc", "abc")) is $(D 0).) and `cmp("abc", "abc")` is `0`.)
$(T2 either, $(T2 either,
Return first parameter $(D p) that passes an $(D if (p)) test, e.g. Return first parameter `p` that passes an `if (p)` test, e.g.
$(D either(0, 42, 43)) returns $(D 42).) `either(0, 42, 43)` returns `42`.)
$(T2 equal, $(T2 equal,
Compares ranges for element-by-element equality, e.g. Compares ranges for element-by-element equality, e.g.
$(D equal([1, 2, 3], [1.0, 2.0, 3.0])) returns $(D true).) `equal([1, 2, 3], [1.0, 2.0, 3.0])` returns `true`.)
$(T2 isPermutation, $(T2 isPermutation,
$(D isPermutation([1, 2], [2, 1])) returns $(D true).) `isPermutation([1, 2], [2, 1])` returns `true`.)
$(T2 isSameLength, $(T2 isSameLength,
$(D isSameLength([1, 2, 3], [4, 5, 6])) returns $(D true).) `isSameLength([1, 2, 3], [4, 5, 6])` returns `true`.)
$(T2 levenshteinDistance, $(T2 levenshteinDistance,
$(D levenshteinDistance("kitten", "sitting")) returns $(D 3) by using `levenshteinDistance("kitten", "sitting")` returns `3` by using
the $(LINK2 https://en.wikipedia.org/wiki/Levenshtein_distance, the $(LINK2 https://en.wikipedia.org/wiki/Levenshtein_distance,
Levenshtein distance _algorithm).) Levenshtein distance _algorithm).)
$(T2 levenshteinDistanceAndPath, $(T2 levenshteinDistanceAndPath,
$(D levenshteinDistanceAndPath("kitten", "sitting")) returns `levenshteinDistanceAndPath("kitten", "sitting")` returns
$(D tuple(3, "snnnsni")) by using the `tuple(3, "snnnsni")` by using the
$(LINK2 https://en.wikipedia.org/wiki/Levenshtein_distance, $(LINK2 https://en.wikipedia.org/wiki/Levenshtein_distance,
Levenshtein distance _algorithm).) Levenshtein distance _algorithm).)
$(T2 max, $(T2 max,
$(D max(3, 4, 2)) returns $(D 4).) `max(3, 4, 2)` returns `4`.)
$(T2 min, $(T2 min,
$(D min(3, 4, 2)) returns $(D 2).) `min(3, 4, 2)` returns `2`.)
$(T2 mismatch, $(T2 mismatch,
$(D mismatch("oh hi", "ohayo")) returns $(D tuple(" hi", "ayo")).) `mismatch("oh hi", "ohayo")` returns `tuple(" hi", "ayo")`.)
$(T2 predSwitch, $(T2 predSwitch,
$(D 2.predSwitch(1, "one", 2, "two", 3, "three")) returns $(D "two").) `2.predSwitch(1, "one", 2, "two", 3, "three")` returns `"two"`.)
) )
Copyright: Andrei Alexandrescu 2008-. Copyright: Andrei Alexandrescu 2008-.
@ -67,9 +67,9 @@ import std.meta : allSatisfy;
import std.typecons; // : tuple, Tuple, Flag, Yes; import std.typecons; // : tuple, Tuple, Flag, Yes;
/** /**
Find $(D value) _among $(D values), returning the 1-based index Find `value` _among `values`, returning the 1-based index
of the first matching value in $(D values), or $(D 0) if $(D value) of the first matching value in `values`, or `0` if `value`
is not _among $(D values). The predicate $(D pred) is used to is not _among `values`. The predicate `pred` is used to
compare values, and uses equality by default. compare values, and uses equality by default.
Params: Params:
@ -130,7 +130,7 @@ if (isExpressionTuple!values)
} }
/** /**
Alternatively, $(D values) can be passed at compile-time, allowing for a more Alternatively, `values` can be passed at compile-time, allowing for a more
efficient search, but one that only supports matching on equality: efficient search, but one that only supports matching on equality:
*/ */
@safe unittest @safe unittest
@ -214,19 +214,19 @@ private template indexOfFirstOvershadowingChoiceOnLast(choices...)
Executes and returns one of a collection of handlers based on the type of the Executes and returns one of a collection of handlers based on the type of the
switch object. switch object.
The first choice that $(D switchObject) can be casted to the type The first choice that `switchObject` can be casted to the type
of argument it accepts will be called with $(D switchObject) casted to that of argument it accepts will be called with `switchObject` casted to that
type, and the value it'll return will be returned by $(D castSwitch). type, and the value it'll return will be returned by `castSwitch`.
If a choice's return type is void, the choice must throw an exception, unless If a choice's return type is void, the choice must throw an exception, unless
all the choices are void. In that case, castSwitch itself will return void. all the choices are void. In that case, castSwitch itself will return void.
Throws: If none of the choice matches, a $(D SwitchError) will be thrown. $(D Throws: If none of the choice matches, a `SwitchError` will be thrown. $(D
SwitchError) will also be thrown if not all the choices are void and a void SwitchError) will also be thrown if not all the choices are void and a void
choice was executed without throwing anything. choice was executed without throwing anything.
Params: Params:
choices = The $(D choices) needs to be composed of function or delegate choices = The `choices` needs to be composed of function or delegate
handlers that accept one argument. There can also be a choice that handlers that accept one argument. There can also be a choice that
accepts zero arguments. That choice will be invoked if the $(D accepts zero arguments. That choice will be invoked if the $(D
switchObject) is null. switchObject) is null.
@ -235,7 +235,7 @@ Params:
Returns: Returns:
The value of the selected choice. The value of the selected choice.
Note: $(D castSwitch) can only be used with object types. Note: `castSwitch` can only be used with object types.
*/ */
auto castSwitch(choices...)(Object switchObject) auto castSwitch(choices...)(Object switchObject)
{ {
@ -517,7 +517,7 @@ auto castSwitch(choices...)(Object switchObject)
/** Clamps a value into the given bounds. /** Clamps a value into the given bounds.
This functions is equivalent to $(D max(lower, min(upper,val))). This functions is equivalent to `max(lower, min(upper,val))`.
Params: Params:
val = The value to _clamp. val = The value to _clamp.
@ -525,7 +525,7 @@ Params:
upper = The _upper bound of the _clamp. upper = The _upper bound of the _clamp.
Returns: Returns:
Returns $(D val), if it is between $(D lower) and $(D upper). Returns `val`, if it is between `lower` and `upper`.
Otherwise returns the nearest of the two. Otherwise returns the nearest of the two.
*/ */
@ -582,15 +582,15 @@ do
/********************************** /**********************************
Performs three-way lexicographical comparison on two Performs three-way lexicographical comparison on two
$(REF_ALTTEXT input ranges, isInputRange, std,range,primitives) $(REF_ALTTEXT input ranges, isInputRange, std,range,primitives)
according to predicate $(D pred). Iterating $(D r1) and $(D r2) in according to predicate `pred`. Iterating `r1` and `r2` in
lockstep, $(D cmp) compares each element $(D e1) of $(D r1) with the lockstep, `cmp` compares each element `e1` of `r1` with the
corresponding element $(D e2) in $(D r2). If one of the ranges has been corresponding element `e2` in `r2`. If one of the ranges has been
finished, $(D cmp) returns a negative value if $(D r1) has fewer finished, `cmp` returns a negative value if `r1` has fewer
elements than $(D r2), a positive value if $(D r1) has more elements elements than `r2`, a positive value if `r1` has more elements
than $(D r2), and $(D 0) if the ranges have the same number of than `r2`, and `0` if the ranges have the same number of
elements. elements.
If the ranges are strings, $(D cmp) performs UTF decoding If the ranges are strings, `cmp` performs UTF decoding
appropriately and compares the ranges one code point at a time. appropriately and compares the ranges one code point at a time.
Params: Params:
@ -600,9 +600,9 @@ Params:
Returns: Returns:
0 if both ranges compare equal. -1 if the first differing element of $(D 0 if both ranges compare equal. -1 if the first differing element of $(D
r1) is less than the corresponding element of $(D r2) according to $(D r1) is less than the corresponding element of `r2` according to $(D
pred). 1 if the first differing element of $(D r2) is less than the pred). 1 if the first differing element of `r2` is less than the
corresponding element of $(D r1) according to $(D pred). corresponding element of `r1` according to `pred`.
*/ */
int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2) int cmp(alias pred = "a < b", R1, R2)(R1 r1, R2 r2)
@ -726,8 +726,8 @@ if (isInputRange!R1 && isInputRange!R2)
// equal // equal
/** /**
Compares two ranges for equality, as defined by predicate $(D pred) Compares two ranges for equality, as defined by predicate `pred`
(which is $(D ==) by default). (which is `==` by default).
*/ */
template equal(alias pred = "a == b") template equal(alias pred = "a == b")
{ {
@ -738,17 +738,17 @@ template equal(alias pred = "a == b")
/++ /++
Compares two ranges for equality. The ranges may have Compares two ranges for equality. The ranges may have
different element types, as long as $(D pred(r1.front, r2.front)) different element types, as long as `pred(r1.front, r2.front)`
evaluates to $(D bool). evaluates to `bool`.
Performs $(BIGOH min(r1.length, r2.length)) evaluations of $(D pred). Performs $(BIGOH min(r1.length, r2.length)) evaluations of `pred`.
Params: Params:
r1 = The first range to be compared. r1 = The first range to be compared.
r2 = The second range to be compared. r2 = The second range to be compared.
Returns: Returns:
$(D true) if and only if the two ranges compare _equal element `true` if and only if the two ranges compare _equal element
for element, according to binary predicate $(D pred). for element, according to binary predicate `pred`.
See_Also: See_Also:
$(HTTP sgi.com/tech/stl/_equal.html, STL's _equal) $(HTTP sgi.com/tech/stl/_equal.html, STL's _equal)
@ -844,9 +844,9 @@ template equal(alias pred = "a == b")
} }
/++ /++
Tip: $(D equal) can itself be used as a predicate to other functions. Tip: `equal` can itself be used as a predicate to other functions.
This can be very useful when the element type of a range is itself a This can be very useful when the element type of a range is itself a
range. In particular, $(D equal) can be its own predicate, allowing range. In particular, `equal` can be its own predicate, allowing
range of range (of range...) comparisons. range of range (of range...) comparisons.
+/ +/
@safe unittest @safe unittest
@ -983,10 +983,10 @@ if (T.length >= 1)
/** /**
Encodes $(HTTP realityinteractive.com/rgrzywinski/archives/000249.html, Encodes $(HTTP realityinteractive.com/rgrzywinski/archives/000249.html,
edit operations) necessary to transform one sequence into edit operations) necessary to transform one sequence into
another. Given sequences $(D s) (source) and $(D t) (target), a another. Given sequences `s` (source) and `t` (target), a
sequence of $(D EditOp) encodes the steps that need to be taken to sequence of `EditOp` encodes the steps that need to be taken to
convert $(D s) into $(D t). For example, if $(D s = "cat") and $(D convert `s` into `t`. For example, if `s = "cat"` and $(D
"cars"), the minimal sequence that transforms $(D s) into $(D t) is: "cars"), the minimal sequence that transforms `s` into `t` is:
skip two characters, replace 't' with 'r', and insert an 's'. Working skip two characters, replace 't' with 'r', and insert an 's'. Working
with edit operations is useful in applications such as spell-checkers with edit operations is useful in applications such as spell-checkers
(to find the closest word to a given misspelled word), approximate (to find the closest word to a given misspelled word), approximate
@ -1193,9 +1193,9 @@ private:
/** /**
Returns the $(HTTP wikipedia.org/wiki/Levenshtein_distance, Levenshtein Returns the $(HTTP wikipedia.org/wiki/Levenshtein_distance, Levenshtein
distance) between $(D s) and $(D t). The Levenshtein distance computes distance) between `s` and `t`. The Levenshtein distance computes
the minimal amount of edit operations necessary to transform $(D s) the minimal amount of edit operations necessary to transform `s`
into $(D t). Performs $(BIGOH s.length * t.length) evaluations of $(D into `t`. Performs $(BIGOH s.length * t.length) evaluations of $(D
equals) and occupies $(BIGOH s.length * t.length) storage. equals) and occupies $(BIGOH s.length * t.length) storage.
Params: Params:
@ -1305,8 +1305,8 @@ if (isConvertibleToString!Range1 || isConvertibleToString!Range2)
} }
/** /**
Returns the Levenshtein distance and the edit path between $(D s) and Returns the Levenshtein distance and the edit path between `s` and
$(D t). `t`.
Params: Params:
equals = The binary predicate to compare the elements of the two ranges. equals = The binary predicate to compare the elements of the two ranges.
@ -1555,11 +1555,11 @@ if (T.length >= 2)
// mismatch // mismatch
/** /**
Sequentially compares elements in $(D r1) and $(D r2) in lockstep, and Sequentially compares elements in `r1` and `r2` in lockstep, and
stops at the first mismatch (according to $(D pred), by default stops at the first mismatch (according to `pred`, by default
equality). Returns a tuple with the reduced ranges that start with the equality). Returns a tuple with the reduced ranges that start with the
two mismatched values. Performs $(BIGOH min(r1.length, r2.length)) two mismatched values. Performs $(BIGOH min(r1.length, r2.length))
evaluations of $(D pred). evaluations of `pred`.
See_Also: See_Also:
$(HTTP sgi.com/tech/stl/_mismatch.html, STL's _mismatch) $(HTTP sgi.com/tech/stl/_mismatch.html, STL's _mismatch)
@ -1598,9 +1598,9 @@ if (isInputRange!(Range1) && isInputRange!(Range2))
Returns one of a collection of expressions based on the value of the switch Returns one of a collection of expressions based on the value of the switch
expression. expression.
$(D choices) needs to be composed of pairs of test expressions and return `choices` needs to be composed of pairs of test expressions and return
expressions. Each test-expression is compared with $(D switchExpression) using expressions. Each test-expression is compared with `switchExpression` using
$(D pred)($(D switchExpression) is the first argument) and if that yields true `pred`(`switchExpression` is the first argument) and if that yields true
- the return expression is returned. - the return expression is returned.
Both the test and the return expressions are lazily evaluated. Both the test and the return expressions are lazily evaluated.
@ -1622,7 +1622,7 @@ made the predicate yield true, or the default return expression if no test
expression matched. expression matched.
Throws: If there is no default return expression and the predicate does not Throws: If there is no default return expression and the predicate does not
yield true with any test expression - $(D SwitchError) is thrown. $(D yield true with any test expression - `SwitchError` is thrown. $(D
SwitchError) is also thrown if a void return expression was executed without SwitchError) is also thrown if a void return expression was executed without
throwing anything. throwing anything.
*/ */
@ -1734,7 +1734,7 @@ auto predSwitch(alias pred = "a == b", T, R ...)(T switchExpression, lazy R choi
/** /**
Checks if the two ranges have the same number of elements. This function is Checks if the two ranges have the same number of elements. This function is
optimized to always take advantage of the $(D length) member of either range optimized to always take advantage of the `length` member of either range
if it exists. if it exists.
If both ranges have a length member, this function is $(BIGOH 1). Otherwise, If both ranges have a length member, this function is $(BIGOH 1). Otherwise,
@ -1745,7 +1745,7 @@ Params:
r2 = a finite $(REF_ALTTEXT input range, isInputRange, std,range,primitives) r2 = a finite $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
Returns: Returns:
$(D true) if both ranges have the same length, $(D false) otherwise. `true` if both ranges have the same length, `false` otherwise.
*/ */
bool isSameLength(Range1, Range2)(Range1 r1, Range2 r2) bool isSameLength(Range1, Range2)(Range1 r1, Range2 r2)
if (isInputRange!Range1 && if (isInputRange!Range1 &&
@ -1867,27 +1867,27 @@ alias AllocateGC = Flag!"allocateGC";
/** /**
Checks if both ranges are permutations of each other. Checks if both ranges are permutations of each other.
This function can allocate if the $(D Yes.allocateGC) flag is passed. This has This function can allocate if the `Yes.allocateGC` flag is passed. This has
the benefit of have better complexity than the $(D Yes.allocateGC) option. However, the benefit of have better complexity than the `Yes.allocateGC` option. However,
this option is only available for ranges whose equality can be determined via each this option is only available for ranges whose equality can be determined via each
element's $(D toHash) method. If customized equality is needed, then the $(D pred) element's `toHash` method. If customized equality is needed, then the `pred`
template parameter can be passed, and the function will automatically switch to template parameter can be passed, and the function will automatically switch to
the non-allocating algorithm. See $(REF binaryFun, std,functional) for more details on the non-allocating algorithm. See $(REF binaryFun, std,functional) for more details on
how to define $(D pred). how to define `pred`.
Non-allocating forward range option: $(BIGOH n^2) Non-allocating forward range option: $(BIGOH n^2)
Non-allocating forward range option with custom $(D pred): $(BIGOH n^2) Non-allocating forward range option with custom `pred`: $(BIGOH n^2)
Allocating forward range option: amortized $(BIGOH r1.length) + $(BIGOH r2.length) Allocating forward range option: amortized $(BIGOH r1.length) + $(BIGOH r2.length)
Params: Params:
pred = an optional parameter to change how equality is defined pred = an optional parameter to change how equality is defined
allocate_gc = $(D Yes.allocateGC)/$(D No.allocateGC) allocate_gc = `Yes.allocateGC`/`No.allocateGC`
r1 = A finite $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) r1 = A finite $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
r2 = A finite $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) r2 = A finite $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
Returns: Returns:
$(D true) if all of the elements in $(D r1) appear the same number of times in $(D r2). `true` if all of the elements in `r1` appear the same number of times in `r2`.
Otherwise, returns $(D false). Otherwise, returns `false`.
*/ */
bool isPermutation(AllocateGC allocate_gc, Range1, Range2) bool isPermutation(AllocateGC allocate_gc, Range1, Range2)

View file

@ -7,48 +7,48 @@ $(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE Cheat Sheet, $(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description)) $(TR $(TH Function Name) $(TH Description))
$(T2 cache, $(T2 cache,
Eagerly evaluates and caches another range's $(D front).) Eagerly evaluates and caches another range's `front`.)
$(T2 cacheBidirectional, $(T2 cacheBidirectional,
As above, but also provides $(D back) and $(D popBack).) As above, but also provides `back` and `popBack`.)
$(T2 chunkBy, $(T2 chunkBy,
$(D chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]])) `chunkBy!((a,b) => a[1] == b[1])([[1, 1], [1, 2], [2, 2], [2, 1]])`
returns a range containing 3 subranges: the first with just returns a range containing 3 subranges: the first with just
$(D [1, 1]); the second with the elements $(D [1, 2]) and $(D [2, 2]); `[1, 1]`; the second with the elements `[1, 2]` and `[2, 2]`;
and the third with just $(D [2, 1]).) and the third with just `[2, 1]`.)
$(T2 cumulativeFold, $(T2 cumulativeFold,
$(D cumulativeFold!((a, b) => a + b)([1, 2, 3, 4])) returns a `cumulativeFold!((a, b) => a + b)([1, 2, 3, 4])` returns a
lazily-evaluated range containing the successive reduced values `1`, lazily-evaluated range containing the successive reduced values `1`,
`3`, `6`, `10`.) `3`, `6`, `10`.)
$(T2 each, $(T2 each,
$(D each!writeln([1, 2, 3])) eagerly prints the numbers $(D 1), $(D 2) `each!writeln([1, 2, 3])` eagerly prints the numbers `1`, `2`
and $(D 3) on their own lines.) and `3` on their own lines.)
$(T2 filter, $(T2 filter,
$(D filter!(a => a > 0)([1, -1, 2, 0, -3])) iterates over elements $(D 1) `filter!(a => a > 0)([1, -1, 2, 0, -3])` iterates over elements `1`
and $(D 2).) and `2`.)
$(T2 filterBidirectional, $(T2 filterBidirectional,
Similar to $(D filter), but also provides $(D back) and $(D popBack) at Similar to `filter`, but also provides `back` and `popBack` at
a small increase in cost.) a small increase in cost.)
$(T2 fold, $(T2 fold,
$(D fold!((a, b) => a + b)([1, 2, 3, 4])) returns $(D 10).) `fold!((a, b) => a + b)([1, 2, 3, 4])` returns `10`.)
$(T2 group, $(T2 group,
$(D group([5, 2, 2, 3, 3])) returns a range containing the tuples `group([5, 2, 2, 3, 3])` returns a range containing the tuples
$(D tuple(5, 1)), $(D tuple(2, 2)), and $(D tuple(3, 2)).) `tuple(5, 1)`, `tuple(2, 2)`, and `tuple(3, 2)`.)
$(T2 joiner, $(T2 joiner,
$(D joiner(["hello", "world!"], "; ")) returns a range that iterates `joiner(["hello", "world!"], "; ")` returns a range that iterates
over the characters $(D "hello; world!"). No new string is created - over the characters `"hello; world!"`. No new string is created -
the existing inputs are iterated.) the existing inputs are iterated.)
$(T2 map, $(T2 map,
$(D map!(a => a * 2)([1, 2, 3])) lazily returns a range with the numbers `map!(a => a * 2)([1, 2, 3])` lazily returns a range with the numbers
$(D 2), $(D 4), $(D 6).) `2`, `4`, `6`.)
$(T2 permutations, $(T2 permutations,
Lazily computes all permutations using Heap's algorithm.) Lazily computes all permutations using Heap's algorithm.)
$(T2 reduce, $(T2 reduce,
$(D reduce!((a, b) => a + b)([1, 2, 3, 4])) returns $(D 10). `reduce!((a, b) => a + b)([1, 2, 3, 4])` returns `10`.
This is the old implementation of `fold`.) This is the old implementation of `fold`.)
$(T2 splitter, $(T2 splitter,
Lazily splits a range by a separator.) Lazily splits a range by a separator.)
$(T2 sum, $(T2 sum,
Same as $(D fold), but specialized for accurate summation.) Same as `fold`, but specialized for accurate summation.)
$(T2 uniq, $(T2 uniq,
Iterates over the unique elements in a range, which is assumed sorted.) Iterates over the unique elements in a range, which is assumed sorted.)
) )
@ -117,29 +117,29 @@ if (fun.length >= 1)
} }
/++ /++
$(D cache) eagerly evaluates $(D front) of $(D range) `cache` eagerly evaluates `front` of `range`
on each construction or call to $(D popFront), on each construction or call to `popFront`,
to store the result in a _cache. to store the result in a _cache.
The result is then directly returned when $(D front) is called, The result is then directly returned when `front` is called,
rather than re-evaluated. rather than re-evaluated.
This can be a useful function to place in a chain, after functions This can be a useful function to place in a chain, after functions
that have expensive evaluation, as a lazy alternative to $(REF array, std,array). that have expensive evaluation, as a lazy alternative to $(REF array, std,array).
In particular, it can be placed after a call to $(D map), or before a call In particular, it can be placed after a call to `map`, or before a call
to $(D filter). to `filter`.
$(D cache) may provide `cache` may provide
$(REF_ALTTEXT bidirectional _range, isBidirectionalRange, std,_range,primitives) $(REF_ALTTEXT bidirectional _range, isBidirectionalRange, std,_range,primitives)
iteration if needed, but since this comes at an increased cost, it must be explicitly requested via the iteration if needed, but since this comes at an increased cost, it must be explicitly requested via the
call to $(D cacheBidirectional). Furthermore, a bidirectional _cache will call to `cacheBidirectional`. Furthermore, a bidirectional _cache will
evaluate the "center" element twice, when there is only one element left in evaluate the "center" element twice, when there is only one element left in
the _range. the _range.
$(D cache) does not provide random access primitives, `cache` does not provide random access primitives,
as $(D cache) would be unable to _cache the random accesses. as `cache` would be unable to _cache the random accesses.
If $(D Range) provides slicing primitives, If `Range` provides slicing primitives,
then $(D cache) will provide the same slicing primitives, then `cache` will provide the same slicing primitives,
but $(D hasSlicing!Cache) will not yield true (as the $(REF hasSlicing, std,_range,primitives) but `hasSlicing!Cache` will not yield true (as the $(REF hasSlicing, std,_range,primitives)
trait also checks for random access). trait also checks for random access).
Params: Params:
@ -204,14 +204,14 @@ if (isBidirectionalRange!Range)
} }
/++ /++
Tip: $(D cache) is eager when evaluating elements. If calling front on the Tip: `cache` is eager when evaluating elements. If calling front on the
underlying _range has a side effect, it will be observable before calling underlying _range has a side effect, it will be observable before calling
front on the actual cached _range. front on the actual cached _range.
Furthermore, care should be taken composing $(D cache) with $(REF take, std,_range). Furthermore, care should be taken composing `cache` with $(REF take, std,_range).
By placing $(D take) before $(D cache), then $(D cache) will be "aware" By placing `take` before `cache`, then `cache` will be "aware"
of when the _range ends, and correctly stop caching elements when needed. of when the _range ends, and correctly stop caching elements when needed.
If calling front has no side effect though, placing $(D take) after $(D cache) If calling front has no side effect though, placing `take` after `cache`
may yield a faster _range. may yield a faster _range.
Either way, the resulting ranges will be equivalent, but maybe not at the Either way, the resulting ranges will be equivalent, but maybe not at the
@ -440,12 +440,12 @@ private struct _Cache(R, bool bidir)
} }
/** /**
$(D auto map(Range)(Range r) if (isInputRange!(Unqual!Range));) `auto map(Range)(Range r) if (isInputRange!(Unqual!Range));`
Implements the homonym function (also known as $(D transform)) present Implements the homonym function (also known as `transform`) present
in many languages of functional flavor. The call $(D map!(fun)(range)) in many languages of functional flavor. The call `map!(fun)(range)`
returns a range of which elements are obtained by applying $(D fun(a)) returns a range of which elements are obtained by applying `fun(a)`
left to right for all elements $(D a) in $(D range). The original ranges are left to right for all elements `a` in `range`. The original ranges are
not changed. Evaluation is done lazily. not changed. Evaluation is done lazily.
Params: Params:
@ -454,7 +454,7 @@ Params:
Returns: Returns:
a range with each fun applied to all the elements. If there is more than one a range with each fun applied to all the elements. If there is more than one
fun, the element type will be $(D Tuple) containing one element for each fun. fun, the element type will be `Tuple` containing one element for each fun.
See_Also: See_Also:
$(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function)) $(HTTP en.wikipedia.org/wiki/Map_(higher-order_function), Map (higher-order function))
@ -508,8 +508,8 @@ if (fun.length >= 1)
} }
/** /**
Multiple functions can be passed to $(D map). In that case, the Multiple functions can be passed to `map`. In that case, the
element type of $(D map) is a tuple containing one element for each element type of `map` is a tuple containing one element for each
function. function.
*/ */
@safe unittest @safe unittest
@ -527,7 +527,7 @@ function.
} }
/** /**
You may alias $(D map) with some function(s) to a symbol and use You may alias `map` with some function(s) to a symbol and use
it separately: it separately:
*/ */
@safe unittest @safe unittest
@ -844,14 +844,14 @@ private struct MapResult(alias fun, Range)
// each // each
/** /**
Eagerly iterates over $(D r) and calls $(D pred) over _each element. Eagerly iterates over `r` and calls `pred` over _each element.
If no predicate is specified, $(D each) will default to doing nothing If no predicate is specified, `each` will default to doing nothing
but consuming the entire range. $(D .front) will be evaluated, but this but consuming the entire range. `.front` will be evaluated, but this
can be avoided by explicitly specifying a predicate lambda with a can be avoided by explicitly specifying a predicate lambda with a
$(D lazy) parameter. `lazy` parameter.
$(D each) also supports $(D opApply)-based iterators, so it will work `each` also supports `opApply`-based iterators, so it will work
with e.g. $(REF parallel, std,parallelism). with e.g. $(REF parallel, std,parallelism).
Params: Params:
@ -1081,19 +1081,19 @@ public:
// filter // filter
/** /**
$(D auto filter(Range)(Range rs) if (isInputRange!(Unqual!Range));) `auto filter(Range)(Range rs) if (isInputRange!(Unqual!Range));`
Implements the higher order _filter function. The predicate is passed to Implements the higher order _filter function. The predicate is passed to
$(REF unaryFun, std,functional), and can either accept a string, or any callable $(REF unaryFun, std,functional), and can either accept a string, or any callable
that can be executed via $(D pred(element)). that can be executed via `pred(element)`.
Params: Params:
predicate = Function to apply to each element of range predicate = Function to apply to each element of range
range = Input range of elements range = Input range of elements
Returns: Returns:
$(D filter!(predicate)(range)) returns a new range containing only elements $(D x) in $(D range) for `filter!(predicate)(range)` returns a new range containing only elements `x` in `range` for
which $(D predicate(x)) returns $(D true). which `predicate(x)` returns `true`.
See_Also: See_Also:
$(HTTP en.wikipedia.org/wiki/Filter_(higher-order_function), Filter (higher-order function)) $(HTTP en.wikipedia.org/wiki/Filter_(higher-order_function), Filter (higher-order function))
@ -1299,9 +1299,9 @@ private struct FilterResult(alias pred, Range)
} }
/** /**
* $(D auto filterBidirectional(Range)(Range r) if (isBidirectionalRange!(Unqual!Range));) * `auto filterBidirectional(Range)(Range r) if (isBidirectionalRange!(Unqual!Range));`
* *
* Similar to $(D filter), except it defines a * Similar to `filter`, except it defines a
* $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives). * $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives).
* There is a speed disadvantage - the constructor spends time * There is a speed disadvantage - the constructor spends time
* finding the last element in the range that satisfies the filtering * finding the last element in the range that satisfies the filtering
@ -1310,14 +1310,14 @@ private struct FilterResult(alias pred, Range)
* $(REF retro, std,range) can be applied against the filtered range. * $(REF retro, std,range) can be applied against the filtered range.
* *
* The predicate is passed to $(REF unaryFun, std,functional), and can either * The predicate is passed to $(REF unaryFun, std,functional), and can either
* accept a string, or any callable that can be executed via $(D pred(element)). * accept a string, or any callable that can be executed via `pred(element)`.
* *
* Params: * Params:
* pred = Function to apply to each element of range * pred = Function to apply to each element of range
* r = Bidirectional range of elements * r = Bidirectional range of elements
* *
* Returns: * Returns:
* a new range containing only the elements in r for which pred returns $(D true). * a new range containing only the elements in r for which pred returns `true`.
*/ */
template filterBidirectional(alias pred) template filterBidirectional(alias pred)
{ {
@ -1398,22 +1398,22 @@ private struct FilterBidiResult(alias pred, Range)
Groups consecutively equivalent elements into a single tuple of the element and Groups consecutively equivalent elements into a single tuple of the element and
the number of its repetitions. the number of its repetitions.
Similarly to $(D uniq), $(D group) produces a range that iterates over unique Similarly to `uniq`, `group` produces a range that iterates over unique
consecutive elements of the given range. Each element of this range is a tuple consecutive elements of the given range. Each element of this range is a tuple
of the element and the number of times it is repeated in the original range. of the element and the number of times it is repeated in the original range.
Equivalence of elements is assessed by using the predicate $(D pred), which Equivalence of elements is assessed by using the predicate `pred`, which
defaults to $(D "a == b"). The predicate is passed to $(REF binaryFun, std,functional), defaults to `"a == b"`. The predicate is passed to $(REF binaryFun, std,functional),
and can either accept a string, or any callable that can be executed via and can either accept a string, or any callable that can be executed via
$(D pred(element, element)). `pred(element, element)`.
Params: Params:
pred = Binary predicate for determining equivalence of two elements. pred = Binary predicate for determining equivalence of two elements.
r = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) to r = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) to
iterate over. iterate over.
Returns: A range of elements of type $(D Tuple!(ElementType!R, uint)), Returns: A range of elements of type `Tuple!(ElementType!R, uint)`,
representing each consecutively unique element and its respective number of representing each consecutively unique element and its respective number of
occurrences in that run. This will be an input range if $(D R) is an input occurrences in that run. This will be an input range if `R` is an input
range, and a forward range in all other cases. range, and a forward range in all other cases.
See_Also: $(LREF chunkBy), which chunks an input range into subranges See_Also: $(LREF chunkBy), which chunks an input range into subranges
@ -1886,17 +1886,17 @@ if (isForwardRange!Range)
* In other languages this is often called `partitionBy`, `groupBy` * In other languages this is often called `partitionBy`, `groupBy`
* or `sliceWhen`. * or `sliceWhen`.
* *
* Equivalence is defined by the predicate $(D pred), which can be either * Equivalence is defined by the predicate `pred`, which can be either
* binary, which is passed to $(REF binaryFun, std,functional), or unary, which is * binary, which is passed to $(REF binaryFun, std,functional), or unary, which is
* passed to $(REF unaryFun, std,functional). In the binary form, two _range elements * passed to $(REF unaryFun, std,functional). In the binary form, two _range elements
* $(D a) and $(D b) are considered equivalent if $(D pred(a,b)) is true. In * `a` and `b` are considered equivalent if `pred(a,b)` is true. In
* unary form, two elements are considered equivalent if $(D pred(a) == pred(b)) * unary form, two elements are considered equivalent if `pred(a) == pred(b)`
* is true. * is true.
* *
* This predicate must be an equivalence relation, that is, it must be * This predicate must be an equivalence relation, that is, it must be
* reflexive ($(D pred(x,x)) is always true), symmetric * reflexive (`pred(x,x)` is always true), symmetric
* ($(D pred(x,y) == pred(y,x))), and transitive ($(D pred(x,y) && pred(y,z)) * (`pred(x,y) == pred(y,x)`), and transitive (`pred(x,y) && pred(y,z)`
* implies $(D pred(x,z))). If this is not the case, the range returned by * implies `pred(x,z)`). If this is not the case, the range returned by
* chunkBy may assert at runtime or behave erratically. * chunkBy may assert at runtime or behave erratically.
* *
* Params: * Params:
@ -2128,7 +2128,7 @@ Params:
Returns: Returns:
A range of elements in the joined range. This will be a forward range if A range of elements in the joined range. This will be a forward range if
both outer and inner ranges of $(D RoR) are forward ranges; otherwise it will both outer and inner ranges of `RoR` are forward ranges; otherwise it will
be only an input range. be only an input range.
See_also: See_also:
@ -2726,20 +2726,20 @@ if (isInputRange!RoR && isInputRange!(ElementType!RoR))
} }
/++ /++
Implements the homonym function (also known as $(D accumulate), $(D Implements the homonym function (also known as `accumulate`, $(D
compress), $(D inject), or $(D foldl)) present in various programming compress), `inject`, or `foldl`) present in various programming
languages of functional flavor. There is also $(LREF fold) which does languages of functional flavor. There is also $(LREF fold) which does
the same thing but with the opposite parameter order. the same thing but with the opposite parameter order.
The call $(D reduce!(fun)(seed, range)) first assigns $(D seed) to The call `reduce!(fun)(seed, range)` first assigns `seed` to
an internal variable $(D result), also called the accumulator. an internal variable `result`, also called the accumulator.
Then, for each element $(D x) in $(D range), $(D result = fun(result, x)) Then, for each element `x` in `range`, `result = fun(result, x)`
gets evaluated. Finally, $(D result) is returned. gets evaluated. Finally, `result` is returned.
The one-argument version $(D reduce!(fun)(range)) The one-argument version `reduce!(fun)(range)`
works similarly, but it uses the first element of the range as the works similarly, but it uses the first element of the range as the
seed (the range must be non-empty). seed (the range must be non-empty).
Returns: Returns:
the accumulated $(D result) the accumulated `result`
Params: Params:
fun = one or more functions fun = one or more functions
@ -2751,7 +2751,7 @@ See_Also:
and without the need to use $(LREF tuple) for multiple seeds. This makes it easier and without the need to use $(LREF tuple) for multiple seeds. This makes it easier
to use in UFCS chains. to use in UFCS chains.
$(LREF sum) is similar to $(D reduce!((a, b) => a + b)) that offers $(LREF sum) is similar to `reduce!((a, b) => a + b)` that offers
pairwise summing of floating point numbers. pairwise summing of floating point numbers.
+/ +/
template reduce(fun...) template reduce(fun...)
@ -2764,20 +2764,20 @@ if (fun.length >= 1)
import std.typecons : tuple, isTuple; import std.typecons : tuple, isTuple;
/++ /++
No-seed version. The first element of $(D r) is used as the seed's value. No-seed version. The first element of `r` is used as the seed's value.
For each function $(D f) in $(D fun), the corresponding For each function `f` in `fun`, the corresponding
seed type $(D S) is $(D Unqual!(typeof(f(e, e)))), where $(D e) is an seed type `S` is `Unqual!(typeof(f(e, e)))`, where `e` is an
element of $(D r): $(D ElementType!R) for ranges, element of `r`: `ElementType!R` for ranges,
and $(D ForeachType!R) otherwise. and `ForeachType!R` otherwise.
Once S has been determined, then $(D S s = e;) and $(D s = f(s, e);) Once S has been determined, then `S s = e;` and `s = f(s, e);`
must both be legal. must both be legal.
If $(D r) is empty, an $(D Exception) is thrown. If `r` is empty, an `Exception` is thrown.
Params: Params:
r = an iterable value as defined by $(D isIterable) r = an iterable value as defined by `isIterable`
Returns: Returns:
the final result of the accumulator applied to the iterable the final result of the accumulator applied to the iterable
@ -2804,19 +2804,19 @@ if (fun.length >= 1)
} }
/++ /++
Seed version. The seed should be a single value if $(D fun) is a Seed version. The seed should be a single value if `fun` is a
single function. If $(D fun) is multiple functions, then $(D seed) single function. If `fun` is multiple functions, then `seed`
should be a $(REF Tuple, std,typecons), with one field per function in $(D f). should be a $(REF Tuple, std,typecons), with one field per function in `f`.
For convenience, if the seed is const, or has qualified fields, then For convenience, if the seed is const, or has qualified fields, then
$(D reduce) will operate on an unqualified copy. If this happens `reduce` will operate on an unqualified copy. If this happens
then the returned type will not perfectly match $(D S). then the returned type will not perfectly match `S`.
Use $(D fold) instead of $(D reduce) to use the seed version in a UFCS chain. Use `fold` instead of `reduce` to use the seed version in a UFCS chain.
Params: Params:
seed = the initial value of the accumulator seed = the initial value of the accumulator
r = an iterable value as defined by $(D isIterable) r = an iterable value as defined by `isIterable`
Returns: Returns:
the final result of the accumulator applied to the iterable the final result of the accumulator applied to the iterable
@ -2891,8 +2891,8 @@ if (fun.length >= 1)
} }
/** /**
Many aggregate range operations turn out to be solved with $(D reduce) Many aggregate range operations turn out to be solved with `reduce`
quickly and easily. The example below illustrates $(D reduce)'s quickly and easily. The example below illustrates `reduce`'s
remarkable power and flexibility. remarkable power and flexibility.
*/ */
@safe unittest @safe unittest
@ -2945,8 +2945,8 @@ remarkable power and flexibility.
/** /**
Sometimes it is very useful to compute multiple aggregates in one pass. Sometimes it is very useful to compute multiple aggregates in one pass.
One advantage is that the computation is faster because the looping overhead One advantage is that the computation is faster because the looping overhead
is shared. That's why $(D reduce) accepts multiple functions. is shared. That's why `reduce` accepts multiple functions.
If two or more functions are passed, $(D reduce) returns a If two or more functions are passed, `reduce` returns a
$(REF Tuple, std,typecons) object with one member per passed-in function. $(REF Tuple, std,typecons) object with one member per passed-in function.
The number of seeds must be correspondingly increased. The number of seeds must be correspondingly increased.
*/ */
@ -3187,23 +3187,23 @@ private template ReduceSeedType(E)
/++ /++
Implements the homonym function (also known as $(D accumulate), $(D Implements the homonym function (also known as `accumulate`, $(D
compress), $(D inject), or $(D foldl)) present in various programming compress), `inject`, or `foldl`) present in various programming
languages of functional flavor. The call $(D fold!(fun)(range, seed)) languages of functional flavor. The call `fold!(fun)(range, seed)`
first assigns $(D seed) to an internal variable $(D result), first assigns `seed` to an internal variable `result`,
also called the accumulator. Then, for each element $(D x) in $(D also called the accumulator. Then, for each element `x` in $(D
range), $(D result = fun(result, x)) gets evaluated. Finally, $(D range), `result = fun(result, x)` gets evaluated. Finally, $(D
result) is returned. The one-argument version $(D fold!(fun)(range)) result) is returned. The one-argument version `fold!(fun)(range)`
works similarly, but it uses the first element of the range as the works similarly, but it uses the first element of the range as the
seed (the range must be non-empty). seed (the range must be non-empty).
Returns: Returns:
the accumulated $(D result) the accumulated `result`
See_Also: See_Also:
$(HTTP en.wikipedia.org/wiki/Fold_(higher-order_function), Fold (higher-order function)) $(HTTP en.wikipedia.org/wiki/Fold_(higher-order_function), Fold (higher-order function))
$(LREF sum) is similar to $(D fold!((a, b) => a + b)) that offers $(LREF sum) is similar to `fold!((a, b) => a + b)` that offers
precise summing of floating point numbers. precise summing of floating point numbers.
This is functionally equivalent to $(LREF reduce) with the argument order reversed, This is functionally equivalent to $(LREF reduce) with the argument order reversed,
@ -3265,12 +3265,12 @@ if (fun.length >= 1)
/++ /++
Similar to `fold`, but returns a range containing the successive reduced values. Similar to `fold`, but returns a range containing the successive reduced values.
The call $(D cumulativeFold!(fun)(range, seed)) first assigns `seed` to an The call `cumulativeFold!(fun)(range, seed)` first assigns `seed` to an
internal variable `result`, also called the accumulator. internal variable `result`, also called the accumulator.
The returned range contains the values $(D result = fun(result, x)) lazily The returned range contains the values `result = fun(result, x)` lazily
evaluated for each element `x` in `range`. Finally, the last element has the evaluated for each element `x` in `range`. Finally, the last element has the
same value as $(D fold!(fun)(seed, range)). same value as `fold!(fun)(seed, range)`.
The one-argument version $(D cumulativeFold!(fun)(range)) works similarly, but The one-argument version `cumulativeFold!(fun)(range)` works similarly, but
it returns the first element unchanged and uses it as seed for the next it returns the first element unchanged and uses it as seed for the next
elements. elements.
This function is also known as This function is also known as
@ -3299,9 +3299,9 @@ if (fun.length >= 1)
/++ /++
No-seed version. The first element of `r` is used as the seed's value. No-seed version. The first element of `r` is used as the seed's value.
For each function `f` in `fun`, the corresponding seed type `S` is For each function `f` in `fun`, the corresponding seed type `S` is
$(D Unqual!(typeof(f(e, e)))), where `e` is an element of `r`: `Unqual!(typeof(f(e, e)))`, where `e` is an element of `r`:
`ElementType!R`. `ElementType!R`.
Once `S` has been determined, then $(D S s = e;) and $(D s = f(s, e);) must Once `S` has been determined, then `S s = e;` and `s = f(s, e);` must
both be legal. both be legal.
Params: Params:
@ -3657,33 +3657,33 @@ any narrow string type or sliceable range type, but is most popular with string
types. types.
Two adjacent separators are considered to surround an empty element in Two adjacent separators are considered to surround an empty element in
the split range. Use $(D filter!(a => !a.empty)) on the result to compress the split range. Use `filter!(a => !a.empty)` on the result to compress
empty elements. empty elements.
The predicate is passed to $(REF binaryFun, std,functional), and can either accept The predicate is passed to $(REF binaryFun, std,functional), and can either accept
a string, or any callable that can be executed via $(D pred(element, s)). a string, or any callable that can be executed via `pred(element, s)`.
If the empty range is given, the result is an empty range. If a range with If the empty range is given, the result is an empty range. If a range with
one separator is given, the result is a range with two empty elements. one separator is given, the result is a range with two empty elements.
If splitting a string on whitespace and token compression is desired, If splitting a string on whitespace and token compression is desired,
consider using $(D splitter) without specifying a separator (see fourth overload consider using `splitter` without specifying a separator (see fourth overload
below). below).
Params: Params:
pred = The predicate for comparing each element with the separator, pred = The predicate for comparing each element with the separator,
defaulting to $(D "a == b"). defaulting to `"a == b"`.
r = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) to be r = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) to be
split. Must support slicing and $(D .length). split. Must support slicing and `.length`.
s = The element to be treated as the separator between range segments to be s = The element to be treated as the separator between range segments to be
split. split.
Constraints: Constraints:
The predicate $(D pred) needs to accept an element of $(D r) and the The predicate `pred` needs to accept an element of `r` and the
separator $(D s). separator `s`.
Returns: Returns:
An input range of the subranges of elements between separators. If $(D r) An input range of the subranges of elements between separators. If `r`
is a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) is a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
or $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives), or $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives),
the returned range will be likewise. the returned range will be likewise.
@ -3965,33 +3965,33 @@ if (is(typeof(binaryFun!pred(r.front, s)) : bool)
} }
/** /**
Similar to the previous overload of $(D splitter), except this one uses another Similar to the previous overload of `splitter`, except this one uses another
range as a separator. This can be used with any narrow string type or sliceable range as a separator. This can be used with any narrow string type or sliceable
range type, but is most popular with string types. The predicate is passed to range type, but is most popular with string types. The predicate is passed to
$(REF binaryFun, std,functional), and can either accept a string, or any callable $(REF binaryFun, std,functional), and can either accept a string, or any callable
that can be executed via $(D pred(r.front, s.front)). that can be executed via `pred(r.front, s.front)`.
Two adjacent separators are considered to surround an empty element in Two adjacent separators are considered to surround an empty element in
the split range. Use $(D filter!(a => !a.empty)) on the result to compress the split range. Use `filter!(a => !a.empty)` on the result to compress
empty elements. empty elements.
Unlike the previous overload of $(D splitter), this one will not return a Unlike the previous overload of `splitter`, this one will not return a
bidirectional range. bidirectional range.
Params: Params:
pred = The predicate for comparing each element with the separator, pred = The predicate for comparing each element with the separator,
defaulting to $(D "a == b"). defaulting to `"a == b"`.
r = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) to be r = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) to be
split. split.
s = The $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) to s = The $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) to
be treated as the separator between segments of $(D r) to be split. be treated as the separator between segments of `r` to be split.
Constraints: Constraints:
The predicate $(D pred) needs to accept an element of $(D r) and an The predicate `pred` needs to accept an element of `r` and an
element of $(D s). element of `s`.
Returns: Returns:
An input range of the subranges of elements between separators. If $(D r) An input range of the subranges of elements between separators. If `r`
is a forward range, the returned range will be a forward range. is a forward range, the returned range will be a forward range.
See_Also: $(REF _splitter, std,regex) for a version that splits using a regular See_Also: $(REF _splitter, std,regex) for a version that splits using a regular
@ -4236,13 +4236,13 @@ if (is(typeof(binaryFun!pred(r.front, s.front)) : bool)
/** /**
Similar to the previous overload of $(D splitter), except this one does not use a separator. Similar to the previous overload of `splitter`, except this one does not use a separator.
Instead, the predicate is an unary function on the input range's element type. Instead, the predicate is an unary function on the input range's element type.
The $(D isTerminator) predicate is passed to $(REF unaryFun, std,functional) and can The `isTerminator` predicate is passed to $(REF unaryFun, std,functional) and can
either accept a string, or any callable that can be executed via $(D pred(element, s)). either accept a string, or any callable that can be executed via `pred(element, s)`.
Two adjacent separators are considered to surround an empty element in Two adjacent separators are considered to surround an empty element in
the split range. Use $(D filter!(a => !a.empty)) on the result to compress the split range. Use `filter!(a => !a.empty)` on the result to compress
empty elements. empty elements.
Params: Params:
@ -4251,10 +4251,10 @@ Params:
be split. be split.
Constraints: Constraints:
The predicate $(D isTerminator) needs to accept an element of $(D input). The predicate `isTerminator` needs to accept an element of `input`.
Returns: Returns:
An input range of the subranges of elements between separators. If $(D input) An input range of the subranges of elements between separators. If `input`
is a forward range or $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives), is a forward range or $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives),
the returned range will be likewise. the returned range will be likewise.
@ -4494,10 +4494,10 @@ private struct SplitterResult(alias isTerminator, Range)
} }
/++ /++
Lazily splits the string $(D s) into words, using whitespace as the delimiter. Lazily splits the string `s` into words, using whitespace as the delimiter.
This function is string specific and, contrary to This function is string specific and, contrary to
$(D splitter!(std.uni.isWhite)), runs of whitespace will be merged together `splitter!(std.uni.isWhite)`, runs of whitespace will be merged together
(no empty tokens will be produced). (no empty tokens will be produced).
Params: Params:
@ -4688,43 +4688,43 @@ if (isSomeChar!C)
// sum // sum
/** /**
Sums elements of $(D r), which must be a finite Sums elements of `r`, which must be a finite
$(REF_ALTTEXT input range, isInputRange, std,range,primitives). Although $(REF_ALTTEXT input range, isInputRange, std,range,primitives). Although
conceptually $(D sum(r)) is equivalent to $(LREF fold)!((a, b) => a + conceptually `sum(r)` is equivalent to $(LREF fold)!((a, b) => a +
b)(r, 0), $(D sum) uses specialized algorithms to maximize accuracy, b)(r, 0), `sum` uses specialized algorithms to maximize accuracy,
as follows. as follows.
$(UL $(UL
$(LI If $(D $(REF ElementType, std,range,primitives)!R) is a floating-point $(LI If `$(REF ElementType, std,range,primitives)!R` is a floating-point
type and $(D R) is a type and `R` is a
$(REF_ALTTEXT random-access range, isRandomAccessRange, std,range,primitives) with $(REF_ALTTEXT random-access range, isRandomAccessRange, std,range,primitives) with
length and slicing, then $(D sum) uses the length and slicing, then `sum` uses the
$(HTTP en.wikipedia.org/wiki/Pairwise_summation, pairwise summation) $(HTTP en.wikipedia.org/wiki/Pairwise_summation, pairwise summation)
algorithm.) algorithm.)
$(LI If $(D ElementType!R) is a floating-point type and $(D R) is a $(LI If `ElementType!R` is a floating-point type and `R` is a
finite input range (but not a random-access range with slicing), then finite input range (but not a random-access range with slicing), then
$(D sum) uses the $(HTTP en.wikipedia.org/wiki/Kahan_summation, `sum` uses the $(HTTP en.wikipedia.org/wiki/Kahan_summation,
Kahan summation) algorithm.) Kahan summation) algorithm.)
$(LI In all other cases, a simple element by element addition is done.) $(LI In all other cases, a simple element by element addition is done.)
) )
For floating point inputs, calculations are made in For floating point inputs, calculations are made in
$(DDLINK spec/type, Types, $(D real)) $(DDLINK spec/type, Types, `real`)
precision for $(D real) inputs and in $(D double) precision otherwise precision for `real` inputs and in `double` precision otherwise
(Note this is a special case that deviates from $(D fold)'s behavior, (Note this is a special case that deviates from `fold`'s behavior,
which would have kept $(D float) precision for a $(D float) range). which would have kept `float` precision for a `float` range).
For all other types, the calculations are done in the same type obtained For all other types, the calculations are done in the same type obtained
from from adding two elements of the range, which may be a different from from adding two elements of the range, which may be a different
type from the elements themselves (for example, in case of type from the elements themselves (for example, in case of
$(DDSUBLINK spec/type,integer-promotions, integral promotion)). $(DDSUBLINK spec/type,integer-promotions, integral promotion)).
A seed may be passed to $(D sum). Not only will this seed be used as an initial A seed may be passed to `sum`. Not only will this seed be used as an initial
value, but its type will override all the above, and determine the algorithm value, but its type will override all the above, and determine the algorithm
and precision used for summation. and precision used for summation.
Note that these specialized summing algorithms execute more primitive operations Note that these specialized summing algorithms execute more primitive operations
than vanilla summation. Therefore, if in certain cases maximum speed is required than vanilla summation. Therefore, if in certain cases maximum speed is required
at expense of precision, one can use $(D fold!((a, b) => a + b)(r, 0)), which at expense of precision, one can use `fold!((a, b) => a + b)(r, 0)`, which
is not specialized for summation. is not specialized for summation.
Params: Params:
@ -5115,10 +5115,10 @@ if (isInputRange!R &&
Lazily iterates unique consecutive elements of the given range (functionality Lazily iterates unique consecutive elements of the given range (functionality
akin to the $(HTTP wikipedia.org/wiki/_Uniq, _uniq) system akin to the $(HTTP wikipedia.org/wiki/_Uniq, _uniq) system
utility). Equivalence of elements is assessed by using the predicate utility). Equivalence of elements is assessed by using the predicate
$(D pred), by default $(D "a == b"). The predicate is passed to `pred`, by default `"a == b"`. The predicate is passed to
$(REF binaryFun, std,functional), and can either accept a string, or any callable $(REF binaryFun, std,functional), and can either accept a string, or any callable
that can be executed via $(D pred(element, element)). If the given range is that can be executed via `pred(element, element)`. If the given range is
bidirectional, $(D uniq) also yields a bidirectional, `uniq` also yields a
$(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives). $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives).
Params: Params:
@ -5128,7 +5128,7 @@ Params:
Returns: Returns:
An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) of An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) of
consecutively unique elements in the original range. If $(D r) is also a consecutively unique elements in the original range. If `r` is also a
forward range or bidirectional range, the returned range will be likewise. forward range or bidirectional range, the returned range will be likewise.
*/ */
auto uniq(alias pred = "a == b", Range)(Range r) auto uniq(alias pred = "a == b", Range)(Range r)
@ -5261,12 +5261,12 @@ private struct UniqResult(alias pred, Range)
} }
/** /**
Lazily computes all _permutations of $(D r) using $(HTTP Lazily computes all _permutations of `r` using $(HTTP
en.wikipedia.org/wiki/Heap%27s_algorithm, Heap's algorithm). en.wikipedia.org/wiki/Heap%27s_algorithm, Heap's algorithm).
Returns: Returns:
A $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) A $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
the elements of which are an $(REF indexed, std,range) view into $(D r). the elements of which are an $(REF indexed, std,range) view into `r`.
See_Also: See_Also:
$(REF nextPermutation, std,algorithm,sorting). $(REF nextPermutation, std,algorithm,sorting).

View file

@ -7,53 +7,53 @@ $(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE Cheat Sheet, $(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description)) $(TR $(TH Function Name) $(TH Description))
$(T2 bringToFront, $(T2 bringToFront,
If $(D a = [1, 2, 3]) and $(D b = [4, 5, 6, 7]), If `a = [1, 2, 3]` and `b = [4, 5, 6, 7]`,
$(D bringToFront(a, b)) leaves $(D a = [4, 5, 6]) and `bringToFront(a, b)` leaves `a = [4, 5, 6]` and
$(D b = [7, 1, 2, 3]).) `b = [7, 1, 2, 3]`.)
$(T2 copy, $(T2 copy,
Copies a range to another. If Copies a range to another. If
$(D a = [1, 2, 3]) and $(D b = new int[5]), then $(D copy(a, b)) `a = [1, 2, 3]` and `b = new int[5]`, then `copy(a, b)`
leaves $(D b = [1, 2, 3, 0, 0]) and returns $(D b[3 .. $]).) leaves `b = [1, 2, 3, 0, 0]` and returns `b[3 .. $]`.)
$(T2 fill, $(T2 fill,
Fills a range with a pattern, Fills a range with a pattern,
e.g., if $(D a = new int[3]), then $(D fill(a, 4)) e.g., if `a = new int[3]`, then `fill(a, 4)`
leaves $(D a = [4, 4, 4]) and $(D fill(a, [3, 4])) leaves leaves `a = [4, 4, 4]` and `fill(a, [3, 4])` leaves
$(D a = [3, 4, 3]).) `a = [3, 4, 3]`.)
$(T2 initializeAll, $(T2 initializeAll,
If $(D a = [1.2, 3.4]), then $(D initializeAll(a)) leaves If `a = [1.2, 3.4]`, then `initializeAll(a)` leaves
$(D a = [double.init, double.init]).) `a = [double.init, double.init]`.)
$(T2 move, $(T2 move,
$(D move(a, b)) moves $(D a) into $(D b). $(D move(a)) reads $(D a) `move(a, b)` moves `a` into `b`. `move(a)` reads `a`
destructively when necessary.) destructively when necessary.)
$(T2 moveEmplace, $(T2 moveEmplace,
Similar to $(D move) but assumes `target` is uninitialized.) Similar to `move` but assumes `target` is uninitialized.)
$(T2 moveAll, $(T2 moveAll,
Moves all elements from one range to another.) Moves all elements from one range to another.)
$(T2 moveEmplaceAll, $(T2 moveEmplaceAll,
Similar to $(D moveAll) but assumes all elements in `target` are uninitialized.) Similar to `moveAll` but assumes all elements in `target` are uninitialized.)
$(T2 moveSome, $(T2 moveSome,
Moves as many elements as possible from one range to another.) Moves as many elements as possible from one range to another.)
$(T2 moveEmplaceSome, $(T2 moveEmplaceSome,
Similar to $(D moveSome) but assumes all elements in `target` are uninitialized.) Similar to `moveSome` but assumes all elements in `target` are uninitialized.)
$(T2 remove, $(T2 remove,
Removes elements from a range in-place, and returns the shortened Removes elements from a range in-place, and returns the shortened
range.) range.)
$(T2 reverse, $(T2 reverse,
If $(D a = [1, 2, 3]), $(D reverse(a)) changes it to $(D [3, 2, 1]).) If `a = [1, 2, 3]`, `reverse(a)` changes it to `[3, 2, 1]`.)
$(T2 strip, $(T2 strip,
Strips all leading and trailing elements equal to a value, or that Strips all leading and trailing elements equal to a value, or that
satisfy a predicate. satisfy a predicate.
If $(D a = [1, 1, 0, 1, 1]), then $(D strip(a, 1)) and If `a = [1, 1, 0, 1, 1]`, then `strip(a, 1)` and
$(D strip!(e => e == 1)(a)) returns $(D [0]).) `strip!(e => e == 1)(a)` returns `[0]`.)
$(T2 stripLeft, $(T2 stripLeft,
Strips all leading elements equal to a value, or that satisfy a Strips all leading elements equal to a value, or that satisfy a
predicate. If $(D a = [1, 1, 0, 1, 1]), then $(D stripLeft(a, 1)) and predicate. If `a = [1, 1, 0, 1, 1]`, then `stripLeft(a, 1)` and
$(D stripLeft!(e => e == 1)(a)) returns $(D [0, 1, 1]).) `stripLeft!(e => e == 1)(a)` returns `[0, 1, 1]`.)
$(T2 stripRight, $(T2 stripRight,
Strips all trailing elements equal to a value, or that satisfy a Strips all trailing elements equal to a value, or that satisfy a
predicate. predicate.
If $(D a = [1, 1, 0, 1, 1]), then $(D stripRight(a, 1)) and If `a = [1, 1, 0, 1, 1]`, then `stripRight(a, 1)` and
$(D stripRight!(e => e == 1)(a)) returns $(D [1, 1, 0]).) `stripRight!(e => e == 1)(a)` returns `[1, 1, 0]`.)
$(T2 swap, $(T2 swap,
Swaps two values.) Swaps two values.)
$(T2 swapAt, $(T2 swapAt,
@ -84,21 +84,21 @@ import std.typecons; // : tuple, Tuple;
// bringToFront // bringToFront
/** /**
The $(D bringToFront) function has considerable flexibility and The `bringToFront` function has considerable flexibility and
usefulness. It can rotate elements in one buffer left or right, swap usefulness. It can rotate elements in one buffer left or right, swap
buffers of equal length, and even move elements across disjoint buffers of equal length, and even move elements across disjoint
buffers of different types and different lengths. buffers of different types and different lengths.
$(D bringToFront) takes two ranges $(D front) and $(D back), which may `bringToFront` takes two ranges `front` and `back`, which may
be of different types. Considering the concatenation of $(D front) and be of different types. Considering the concatenation of `front` and
$(D back) one unified range, $(D bringToFront) rotates that unified `back` one unified range, `bringToFront` rotates that unified
range such that all elements in $(D back) are brought to the beginning range such that all elements in `back` are brought to the beginning
of the unified range. The relative ordering of elements in $(D front) of the unified range. The relative ordering of elements in `front`
and $(D back), respectively, remains unchanged. and `back`, respectively, remains unchanged.
The $(D bringToFront) function treats strings at the code unit The `bringToFront` function treats strings at the code unit
level and it is not concerned with Unicode character integrity. level and it is not concerned with Unicode character integrity.
$(D bringToFront) is designed as a function for moving elements `bringToFront` is designed as a function for moving elements
in ranges, not as a string function. in ranges, not as a string function.
Performs $(BIGOH max(front.length, back.length)) evaluations of $(D Performs $(BIGOH max(front.length, back.length)) evaluations of $(D
@ -106,8 +106,8 @@ swap).
Preconditions: Preconditions:
Either $(D front) and $(D back) are disjoint, or $(D back) is Either `front` and `back` are disjoint, or `back` is
reachable from $(D front) and $(D front) is not reachable from $(D reachable from `front` and `front` is not reachable from $(D
back). back).
Params: Params:
@ -115,7 +115,7 @@ Params:
back = a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) back = a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
Returns: Returns:
The number of elements brought to the front, i.e., the length of $(D back). The number of elements brought to the front, i.e., the length of `back`.
See_Also: See_Also:
$(HTTP sgi.com/tech/stl/_rotate.html, STL's rotate) $(HTTP sgi.com/tech/stl/_rotate.html, STL's rotate)
@ -146,7 +146,7 @@ if (isInputRange!InputRange && isForwardRange!ForwardRange)
} }
/** /**
The simplest use of $(D bringToFront) is for rotating elements in a The simplest use of `bringToFront` is for rotating elements in a
buffer. For example: buffer. For example:
*/ */
@safe unittest @safe unittest
@ -158,10 +158,10 @@ buffer. For example:
} }
/** /**
The $(D front) range may actually "step over" the $(D back) The `front` range may actually "step over" the `back`
range. This is very useful with forward ranges that cannot compute range. This is very useful with forward ranges that cannot compute
comfortably right-bounded subranges like $(D arr[0 .. 4]) above. In comfortably right-bounded subranges like `arr[0 .. 4]` above. In
the example below, $(D r2) is a right subrange of $(D r1). the example below, `r2` is a right subrange of `r1`.
*/ */
@safe unittest @safe unittest
{ {
@ -351,11 +351,11 @@ private enum bool areCopyCompatibleArrays(T1, T2) =
// copy // copy
/** /**
Copies the content of $(D source) into $(D target) and returns the Copies the content of `source` into `target` and returns the
remaining (unfilled) part of $(D target). remaining (unfilled) part of `target`.
Preconditions: $(D target) shall have enough room to accommodate Preconditions: `target` shall have enough room to accommodate
the entirety of $(D source). the entirety of `source`.
Params: Params:
source = an $(REF_ALTTEXT input range, isInputRange, std,range,primitives) source = an $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
@ -446,7 +446,7 @@ range elements, different types of ranges are accepted:
} }
/** /**
To _copy at most $(D n) elements from a range, you may want to use To _copy at most `n` elements from a range, you may want to use
$(REF take, std,range): $(REF take, std,range):
*/ */
@safe unittest @safe unittest
@ -539,7 +539,7 @@ $(HTTP sgi.com/tech/stl/copy_backward.html, STL's copy_backward'):
} }
/** /**
Assigns $(D value) to each element of input _range $(D range). Assigns `value` to each element of input _range `range`.
Params: Params:
range = An range = An
@ -713,9 +713,9 @@ if ((isInputRange!Range && is(typeof(range.front = value)) ||
} }
/** /**
Fills $(D range) with a pattern copied from $(D filler). The length of Fills `range` with a pattern copied from `filler`. The length of
$(D range) does not have to be a multiple of the length of $(D `range` does not have to be a multiple of the length of $(D
filler). If $(D filler) is empty, an exception is thrown. filler). If `filler` is empty, an exception is thrown.
Params: Params:
range = An $(REF_ALTTEXT input _range, isInputRange, std,_range,primitives) range = An $(REF_ALTTEXT input _range, isInputRange, std,_range,primitives)
@ -832,7 +832,7 @@ if (isInputRange!InputRange
} }
/** /**
Initializes all elements of $(D range) with their $(D .init) value. Initializes all elements of `range` with their `.init` value.
Assumes that the elements of the range are uninitialized. Assumes that the elements of the range are uninitialized.
Params: Params:
@ -1447,9 +1447,9 @@ Params:
src = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) with src = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) with
movable elements. movable elements.
tgt = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) with tgt = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) with
elements that elements from $(D src) can be moved into. elements that elements from `src` can be moved into.
Returns: The leftover portion of $(D tgt) after all elements from $(D src) have Returns: The leftover portion of `tgt` after all elements from `src` have
been moved. been moved.
*/ */
InputRange2 moveAll(InputRange1, InputRange2)(InputRange1 src, InputRange2 tgt) InputRange2 moveAll(InputRange1, InputRange2)(InputRange1 src, InputRange2 tgt)
@ -1554,7 +1554,7 @@ Params:
src = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) with src = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) with
movable elements. movable elements.
tgt = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) with tgt = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives) with
elements that elements from $(D src) can be moved into. elements that elements from `src` can be moved into.
Returns: The leftover portions of the two ranges after one or the other of the Returns: The leftover portions of the two ranges after one or the other of the
ranges have been exhausted. ranges have been exhausted.
@ -1624,15 +1624,15 @@ Defines the swapping strategy for algorithms that need to swap
elements in a range (such as partition and sort). The strategy elements in a range (such as partition and sort). The strategy
concerns the swapping of elements that are not the core concern of the concerns the swapping of elements that are not the core concern of the
algorithm. For example, consider an algorithm that sorts $(D [ "abc", algorithm. For example, consider an algorithm that sorts $(D [ "abc",
"b", "aBc" ]) according to $(D toUpper(a) < toUpper(b)). That "b", "aBc" ]) according to `toUpper(a) < toUpper(b)`. That
algorithm might choose to swap the two equivalent strings $(D "abc") algorithm might choose to swap the two equivalent strings `"abc"`
and $(D "aBc"). That does not affect the sorting since both $(D [ and `"aBc"`. That does not affect the sorting since both `$D(
"abc", "aBc", "b" ]) and $(D [ "aBc", "abc", "b" ]) are valid "abc", "aBc", "b" ]) and `[ "aBc", "abc", "b" ]` are valid
outcomes. outcomes.
Some situations require that the algorithm must NOT ever change the Some situations require that the algorithm must NOT ever change the
relative ordering of equivalent elements (in the example above, only relative ordering of equivalent elements (in the example above, only
$(D [ "abc", "aBc", "b" ]) would be the correct result). Such `[ "abc", "aBc", "b" ]` would be the correct result). Such
algorithms are called $(B stable). If the ordering algorithm may swap algorithms are called $(B stable). If the ordering algorithm may swap
equivalent elements discretionarily, the ordering is called $(B equivalent elements discretionarily, the ordering is called $(B
unstable). unstable).
@ -1642,12 +1642,12 @@ being stable only on a well-defined subrange of the range. There is no
established terminology for such behavior; this library calls it $(B established terminology for such behavior; this library calls it $(B
semistable). semistable).
Generally, the $(D stable) ordering strategy may be more costly in Generally, the `stable` ordering strategy may be more costly in
time and/or space than the other two because it imposes additional time and/or space than the other two because it imposes additional
constraints. Similarly, $(D semistable) may be costlier than $(D constraints. Similarly, `semistable` may be costlier than $(D
unstable). As (semi-)stability is not needed very often, the ordering unstable). As (semi-)stability is not needed very often, the ordering
algorithms in this module parameterized by $(D SwapStrategy) all algorithms in this module parameterized by `SwapStrategy` all
choose $(D SwapStrategy.unstable) as the default. choose `SwapStrategy.unstable` as the default.
*/ */
enum SwapStrategy enum SwapStrategy
@ -1730,7 +1730,7 @@ invoked to rearrange elements, and on integers `move` simply copies the source
to the destination. To replace `a` with the effect of the removal, simply to the destination. To replace `a` with the effect of the removal, simply
assign the slice returned by `remove` to it, as shown in the first example. assign the slice returned by `remove` to it, as shown in the first example.
Multiple indices can be passed into $(D remove). In that case, Multiple indices can be passed into `remove`. In that case,
elements at the respective indices are all removed. The indices must elements at the respective indices are all removed. The indices must
be passed in increasing order, otherwise an exception occurs. be passed in increasing order, otherwise an exception occurs.
@ -1752,25 +1752,25 @@ assert(remove(a, 1, tuple(3, 5), 9) == [ 0, 2, 5, 6, 7, 8, 10 ]);
In this case, the slots at positions 1, 3, 4, and 9 are removed from In this case, the slots at positions 1, 3, 4, and 9 are removed from
the array. The tuple passes in a range closed to the left and open to the array. The tuple passes in a range closed to the left and open to
the right (consistent with built-in slices), e.g. $(D tuple(3, 5)) the right (consistent with built-in slices), e.g. `tuple(3, 5)`
means indices $(D 3) and $(D 4) but not $(D 5). means indices `3` and `4` but not `5`.
If the need is to remove some elements in the range but the order of If the need is to remove some elements in the range but the order of
the remaining elements does not have to be preserved, you may want to the remaining elements does not have to be preserved, you may want to
pass $(D SwapStrategy.unstable) to $(D remove). pass `SwapStrategy.unstable` to `remove`.
---- ----
int[] a = [ 0, 1, 2, 3 ]; int[] a = [ 0, 1, 2, 3 ];
assert(remove!(SwapStrategy.unstable)(a, 1) == [ 0, 3, 2 ]); assert(remove!(SwapStrategy.unstable)(a, 1) == [ 0, 3, 2 ]);
---- ----
In the case above, the element at slot $(D 1) is removed, but replaced In the case above, the element at slot `1` is removed, but replaced
with the last element of the range. Taking advantage of the relaxation with the last element of the range. Taking advantage of the relaxation
of the stability requirement, $(D remove) moved elements from the end of the stability requirement, `remove` moved elements from the end
of the array over the slots to be removed. This way there is less data of the array over the slots to be removed. This way there is less data
movement to be done which improves the execution time of the function. movement to be done which improves the execution time of the function.
The function $(D remove) works on bidirectional ranges that have assignable The function `remove` works on bidirectional ranges that have assignable
lvalue elements. The moving strategy is (listed from fastest to slowest): lvalue elements. The moving strategy is (listed from fastest to slowest):
$(UL $(LI If $(D s == SwapStrategy.unstable && isRandomAccessRange!Range && $(UL $(LI If $(D s == SwapStrategy.unstable && isRandomAccessRange!Range &&
hasLength!Range && hasLvalueElements!Range), then elements are moved from the hasLength!Range && hasLvalueElements!Range), then elements are moved from the
@ -1779,8 +1779,8 @@ minimum of moves is performed.) $(LI Otherwise, if $(D s ==
SwapStrategy.unstable && isBidirectionalRange!Range && hasLength!Range SwapStrategy.unstable && isBidirectionalRange!Range && hasLength!Range
&& hasLvalueElements!Range), then elements are still moved from the && hasLvalueElements!Range), then elements are still moved from the
end of the range, but time is spent on advancing between slots by repeated end of the range, but time is spent on advancing between slots by repeated
calls to $(D range.popFront).) $(LI Otherwise, elements are moved calls to `range.popFront`.) $(LI Otherwise, elements are moved
incrementally towards the front of $(D range); a given element is never incrementally towards the front of `range`; a given element is never
moved several times, but more elements are moved than in the previous moved several times, but more elements are moved than in the previous
cases.)) cases.))
@ -2021,10 +2021,10 @@ if (s == SwapStrategy.stable
/** /**
Reduces the length of the Reduces the length of the
$(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,_range,primitives) $(D range) by removing $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,_range,primitives) `range` by removing
elements that satisfy $(D pred). If $(D s = SwapStrategy.unstable), elements that satisfy `pred`. If `s = SwapStrategy.unstable`,
elements are moved from the right end of the range over the elements elements are moved from the right end of the range over the elements
to eliminate. If $(D s = SwapStrategy.stable) (the default), to eliminate. If `s = SwapStrategy.stable` (the default),
elements are moved progressively to front such that their relative elements are moved progressively to front such that their relative
order is preserved. Returns the filtered range. order is preserved. Returns the filtered range.
@ -2032,7 +2032,7 @@ Params:
range = a bidirectional ranges with lvalue elements range = a bidirectional ranges with lvalue elements
Returns: Returns:
the range with all of the elements where $(D pred) is $(D true) the range with all of the elements where `pred` is `true`
removed removed
*/ */
Range remove(alias pred, SwapStrategy s = SwapStrategy.stable, Range) Range remove(alias pred, SwapStrategy s = SwapStrategy.stable, Range)
@ -2181,7 +2181,7 @@ if (isBidirectionalRange!Range
// reverse // reverse
/** /**
Reverses $(D r) in-place. Performs $(D r.length / 2) evaluations of $(D Reverses `r` in-place. Performs `r.length / 2` evaluations of $(D
swap). swap).
Params: Params:
r = a $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives) r = a $(REF_ALTTEXT bidirectional range, isBidirectionalRange, std,range,primitives)
@ -2240,18 +2240,18 @@ if (isRandomAccessRange!Range && hasLength!Range)
} }
/** /**
Reverses $(D r) in-place, where $(D r) is a narrow string (having Reverses `r` in-place, where `r` is a narrow string (having
elements of type $(D char) or $(D wchar)). UTF sequences consisting of elements of type `char` or `wchar`). UTF sequences consisting of
multiple code units are preserved properly. multiple code units are preserved properly.
Params: Params:
s = a narrow string s = a narrow string
Bugs: Bugs:
When passing a sting with unicode modifiers on characters, such as $(D \u0301), When passing a sting with unicode modifiers on characters, such as `\u0301`,
this function will not properly keep the position of the modifier. For example, this function will not properly keep the position of the modifier. For example,
reversing $(D ba\u0301d) ("bád") will result in d\u0301ab ("d́ab") instead of reversing `ba\u0301d` ("bád") will result in d\u0301ab ("d́ab") instead of
$(D da\u0301b) ("dáb"). `da\u0301b` ("dáb").
*/ */
void reverse(Char)(Char[] s) void reverse(Char)(Char[] s)
if (isNarrowString!(Char[]) && !is(Char == const) && !is(Char == immutable)) if (isNarrowString!(Char[]) && !is(Char == const) && !is(Char == immutable))
@ -2307,12 +2307,12 @@ if (isNarrowString!(Char[]) && !is(Char == const) && !is(Char == immutable))
The strip group of functions allow stripping of either leading, trailing, The strip group of functions allow stripping of either leading, trailing,
or both leading and trailing elements. or both leading and trailing elements.
The $(D stripLeft) function will strip the $(D front) of the range, The `stripLeft` function will strip the `front` of the range,
the $(D stripRight) function will strip the $(D back) of the range, the `stripRight` function will strip the `back` of the range,
while the $(D strip) function will strip both the $(D front) and $(D back) while the `strip` function will strip both the `front` and `back`
of the range. of the range.
Note that the $(D strip) and $(D stripRight) functions require the range to Note that the `strip` and `stripRight` functions require the range to
be a $(LREF BidirectionalRange) range. be a $(LREF BidirectionalRange) range.
All of these functions come in two varieties: one takes a target element, All of these functions come in two varieties: one takes a target element,
@ -2445,18 +2445,18 @@ if (isBidirectionalRange!Range && is(typeof(pred(range.back)) : bool))
// swap // swap
/** /**
Swaps $(D lhs) and $(D rhs). The instances $(D lhs) and $(D rhs) are moved in Swaps `lhs` and `rhs`. The instances `lhs` and `rhs` are moved in
memory, without ever calling $(D opAssign), nor any other function. $(D T) memory, without ever calling `opAssign`, nor any other function. `T`
need not be assignable at all to be swapped. need not be assignable at all to be swapped.
If $(D lhs) and $(D rhs) reference the same instance, then nothing is done. If `lhs` and `rhs` reference the same instance, then nothing is done.
$(D lhs) and $(D rhs) must be mutable. If $(D T) is a struct or union, then `lhs` and `rhs` must be mutable. If `T` is a struct or union, then
its fields must also all be (recursively) mutable. its fields must also all be (recursively) mutable.
Params: Params:
lhs = Data to be swapped with $(D rhs). lhs = Data to be swapped with `rhs`.
rhs = Data to be swapped with $(D lhs). rhs = Data to be swapped with `lhs`.
*/ */
void swap(T)(ref T lhs, ref T rhs) @trusted pure nothrow @nogc void swap(T)(ref T lhs, ref T rhs) @trusted pure nothrow @nogc
if (isBlitAssignable!T && !is(typeof(lhs.proxySwap(rhs)))) if (isBlitAssignable!T && !is(typeof(lhs.proxySwap(rhs))))
@ -2820,8 +2820,8 @@ if (isInputRange!R1 && isInputRange!R2)
// swapRanges // swapRanges
/** /**
Swaps all elements of $(D r1) with successive elements in $(D r2). Swaps all elements of `r1` with successive elements in `r2`.
Returns a tuple containing the remainder portions of $(D r1) and $(D Returns a tuple containing the remainder portions of `r1` and $(D
r2) that were not swapped (one of them will be empty). The ranges may r2) that were not swapped (one of them will be empty). The ranges may
be of different types but must have the same element type and support be of different types but must have the same element type and support
swapping. swapping.
@ -2860,7 +2860,7 @@ if (hasSwappableElements!InputRange1 && hasSwappableElements!InputRange2
} }
/** /**
Initializes each element of $(D range) with $(D value). Initializes each element of `range` with `value`.
Assumes that the elements of the range are uninitialized. Assumes that the elements of the range are uninitialized.
This is of interest for structs that This is of interest for structs that
define copy constructors (for all other types, $(LREF fill) and define copy constructors (for all other types, $(LREF fill) and

View file

@ -152,12 +152,12 @@ Many functions in this package are parameterized with a $(GLOSSARY predicate).
The predicate may be any suitable callable type The predicate may be any suitable callable type
(a function, a delegate, a $(GLOSSARY functor), or a lambda), or a (a function, a delegate, a $(GLOSSARY functor), or a lambda), or a
compile-time string. The string may consist of $(B any) legal D compile-time string. The string may consist of $(B any) legal D
expression that uses the symbol $(D a) (for unary functions) or the expression that uses the symbol `a` (for unary functions) or the
symbols $(D a) and $(D b) (for binary functions). These names will NOT symbols `a` and `b` (for binary functions). These names will NOT
interfere with other homonym symbols in user code because they are interfere with other homonym symbols in user code because they are
evaluated in a different context. The default for all binary evaluated in a different context. The default for all binary
comparison predicates is $(D "a == b") for unordered operations and comparison predicates is `"a == b"` for unordered operations and
$(D "a < b") for ordered operations. `"a < b"` for ordered operations.
Example: Example:

View file

@ -7,58 +7,58 @@ $(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE Cheat Sheet, $(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description)) $(TR $(TH Function Name) $(TH Description))
$(T2 all, $(T2 all,
$(D all!"a > 0"([1, 2, 3, 4])) returns $(D true) because all elements `all!"a > 0"([1, 2, 3, 4])` returns `true` because all elements
are positive) are positive)
$(T2 any, $(T2 any,
$(D any!"a > 0"([1, 2, -3, -4])) returns $(D true) because at least one `any!"a > 0"([1, 2, -3, -4])` returns `true` because at least one
element is positive) element is positive)
$(T2 balancedParens, $(T2 balancedParens,
$(D balancedParens("((1 + 1) / 2)")) returns $(D true) because the `balancedParens("((1 + 1) / 2)")` returns `true` because the
string has balanced parentheses.) string has balanced parentheses.)
$(T2 boyerMooreFinder, $(T2 boyerMooreFinder,
$(D find("hello world", boyerMooreFinder("or"))) returns $(D "orld") `find("hello world", boyerMooreFinder("or"))` returns `"orld"`
using the $(LINK2 https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm, using the $(LINK2 https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm,
Boyer-Moore _algorithm).) Boyer-Moore _algorithm).)
$(T2 canFind, $(T2 canFind,
$(D canFind("hello world", "or")) returns $(D true).) `canFind("hello world", "or")` returns `true`.)
$(T2 count, $(T2 count,
Counts elements that are equal to a specified value or satisfy a Counts elements that are equal to a specified value or satisfy a
predicate. $(D count([1, 2, 1], 1)) returns $(D 2) and predicate. `count([1, 2, 1], 1)` returns `2` and
$(D count!"a < 0"([1, -3, 0])) returns $(D 1).) `count!"a < 0"([1, -3, 0])` returns `1`.)
$(T2 countUntil, $(T2 countUntil,
$(D countUntil(a, b)) returns the number of steps taken in $(D a) to `countUntil(a, b)` returns the number of steps taken in `a` to
reach $(D b); for example, $(D countUntil("hello!", "o")) returns reach `b`; for example, `countUntil("hello!", "o")` returns
$(D 4).) `4`.)
$(T2 commonPrefix, $(T2 commonPrefix,
$(D commonPrefix("parakeet", "parachute")) returns $(D "para").) `commonPrefix("parakeet", "parachute")` returns `"para"`.)
$(T2 endsWith, $(T2 endsWith,
$(D endsWith("rocks", "ks")) returns $(D true).) `endsWith("rocks", "ks")` returns `true`.)
$(T2 find, $(T2 find,
$(D find("hello world", "or")) returns $(D "orld") using linear search. `find("hello world", "or")` returns `"orld"` using linear search.
(For binary search refer to $(REF sortedRange, std,range).)) (For binary search refer to $(REF sortedRange, std,range).))
$(T2 findAdjacent, $(T2 findAdjacent,
$(D findAdjacent([1, 2, 3, 3, 4])) returns the subrange starting with `findAdjacent([1, 2, 3, 3, 4])` returns the subrange starting with
two equal adjacent elements, i.e. $(D [3, 3, 4]).) two equal adjacent elements, i.e. `[3, 3, 4]`.)
$(T2 findAmong, $(T2 findAmong,
$(D findAmong("abcd", "qcx")) returns $(D "cd") because $(D 'c') is `findAmong("abcd", "qcx")` returns `"cd"` because `'c'` is
among $(D "qcx").) among `"qcx"`.)
$(T2 findSkip, $(T2 findSkip,
If $(D a = "abcde"), then $(D findSkip(a, "x")) returns $(D false) and If `a = "abcde"`, then `findSkip(a, "x")` returns `false` and
leaves $(D a) unchanged, whereas $(D findSkip(a, "c")) advances $(D a) leaves `a` unchanged, whereas `findSkip(a, "c")` advances `a`
to $(D "de") and returns $(D true).) to `"de"` and returns `true`.)
$(T2 findSplit, $(T2 findSplit,
$(D findSplit("abcdefg", "de")) returns the three ranges $(D "abc"), `findSplit("abcdefg", "de")` returns the three ranges `"abc"`,
$(D "de"), and $(D "fg").) `"de"`, and `"fg"`.)
$(T2 findSplitAfter, $(T2 findSplitAfter,
$(D findSplitAfter("abcdefg", "de")) returns the two ranges `findSplitAfter("abcdefg", "de")` returns the two ranges
$(D "abcde") and $(D "fg").) `"abcde"` and `"fg"`.)
$(T2 findSplitBefore, $(T2 findSplitBefore,
$(D findSplitBefore("abcdefg", "de")) returns the two ranges $(D "abc") `findSplitBefore("abcdefg", "de")` returns the two ranges `"abc"`
and $(D "defg").) and `"defg"`.)
$(T2 minCount, $(T2 minCount,
$(D minCount([2, 1, 1, 4, 1])) returns $(D tuple(1, 3)).) `minCount([2, 1, 1, 4, 1])` returns `tuple(1, 3)`.)
$(T2 maxCount, $(T2 maxCount,
$(D maxCount([2, 4, 1, 4, 1])) returns $(D tuple(4, 2)).) `maxCount([2, 4, 1, 4, 1])` returns `tuple(4, 2)`.)
$(T2 minElement, $(T2 minElement,
Selects the minimal element of a range. Selects the minimal element of a range.
`minElement([3, 4, 1, 2])` returns `1`.) `minElement([3, 4, 1, 2])` returns `1`.)
@ -72,22 +72,22 @@ $(T2 maxIndex,
Index of the maximal element of a range. Index of the maximal element of a range.
`maxElement([3, 4, 1, 2])` returns `1`.) `maxElement([3, 4, 1, 2])` returns `1`.)
$(T2 minPos, $(T2 minPos,
$(D minPos([2, 3, 1, 3, 4, 1])) returns the subrange $(D [1, 3, 4, 1]), `minPos([2, 3, 1, 3, 4, 1])` returns the subrange `[1, 3, 4, 1]`,
i.e., positions the range at the first occurrence of its minimal i.e., positions the range at the first occurrence of its minimal
element.) element.)
$(T2 maxPos, $(T2 maxPos,
$(D maxPos([2, 3, 1, 3, 4, 1])) returns the subrange $(D [4, 1]), `maxPos([2, 3, 1, 3, 4, 1])` returns the subrange `[4, 1]`,
i.e., positions the range at the first occurrence of its maximal i.e., positions the range at the first occurrence of its maximal
element.) element.)
$(T2 mismatch, $(T2 mismatch,
$(D mismatch("parakeet", "parachute")) returns the two ranges `mismatch("parakeet", "parachute")` returns the two ranges
$(D "keet") and $(D "chute").) `"keet"` and `"chute"`.)
$(T2 skipOver, $(T2 skipOver,
Assume $(D a = "blah"). Then $(D skipOver(a, "bi")) leaves $(D a) Assume `a = "blah"`. Then `skipOver(a, "bi")` leaves `a`
unchanged and returns $(D false), whereas $(D skipOver(a, "bl")) unchanged and returns `false`, whereas `skipOver(a, "bl")`
advances $(D a) to refer to $(D "ah") and returns $(D true).) advances `a` to refer to `"ah"` and returns `true`.)
$(T2 startsWith, $(T2 startsWith,
$(D startsWith("hello, world", "hello")) returns $(D true).) `startsWith("hello, world", "hello")` returns `true`.)
$(T2 until, $(T2 until,
Lazily iterates a range until a specific value is found.) Lazily iterates a range until a specific value is found.)
) )
@ -113,14 +113,14 @@ import std.traits;
import std.typecons; // : Tuple, Flag, Yes, No; import std.typecons; // : Tuple, Flag, Yes, No;
/++ /++
Checks if $(I _all) of the elements verify $(D pred). Checks if $(I _all) of the elements verify `pred`.
+/ +/
template all(alias pred = "a") template all(alias pred = "a")
{ {
/++ /++
Returns $(D true) if and only if $(I _all) values $(D v) found in the Returns `true` if and only if $(I _all) values `v` found in the
input _range $(D range) satisfy the predicate $(D pred). input _range `range` satisfy the predicate `pred`.
Performs (at most) $(BIGOH range.length) evaluations of $(D pred). Performs (at most) $(BIGOH range.length) evaluations of `pred`.
+/ +/
bool all(Range)(Range range) bool all(Range)(Range range)
if (isInputRange!Range && is(typeof(unaryFun!pred(range.front)))) if (isInputRange!Range && is(typeof(unaryFun!pred(range.front))))
@ -139,7 +139,7 @@ template all(alias pred = "a")
} }
/++ /++
$(D all) can also be used without a predicate, if its items can be `all` can also be used without a predicate, if its items can be
evaluated to true or false in a conditional statement. This can be a evaluated to true or false in a conditional statement. This can be a
convenient way to quickly evaluate that $(I _all) of the elements of a range convenient way to quickly evaluate that $(I _all) of the elements of a range
are true. are true.
@ -157,17 +157,17 @@ are true.
} }
/++ /++
Checks if $(I _any) of the elements verifies $(D pred). Checks if $(I _any) of the elements verifies `pred`.
$(D !any) can be used to verify that $(I none) of the elements verify `!any` can be used to verify that $(I none) of the elements verify
$(D pred). `pred`.
This is sometimes called `exists` in other languages. This is sometimes called `exists` in other languages.
+/ +/
template any(alias pred = "a") template any(alias pred = "a")
{ {
/++ /++
Returns $(D true) if and only if $(I _any) value $(D v) found in the Returns `true` if and only if $(I _any) value `v` found in the
input _range $(D range) satisfies the predicate $(D pred). input _range `range` satisfies the predicate `pred`.
Performs (at most) $(BIGOH range.length) evaluations of $(D pred). Performs (at most) $(BIGOH range.length) evaluations of `pred`.
+/ +/
bool any(Range)(Range range) bool any(Range)(Range range)
if (isInputRange!Range && is(typeof(unaryFun!pred(range.front)))) if (isInputRange!Range && is(typeof(unaryFun!pred(range.front))))
@ -185,8 +185,8 @@ template any(alias pred = "a")
} }
/++ /++
$(D any) can also be used without a predicate, if its items can be `any` can also be used without a predicate, if its items can be
evaluated to true or false in a conditional statement. $(D !any) can be a evaluated to true or false in a conditional statement. `!any` can be a
convenient way to quickly test that $(I none) of the elements of a range convenient way to quickly test that $(I none) of the elements of a range
evaluate to true. evaluate to true.
+/ +/
@ -212,10 +212,10 @@ evaluate to true.
// balancedParens // balancedParens
/** /**
Checks whether $(D r) has "balanced parentheses", i.e. all instances Checks whether `r` has "balanced parentheses", i.e. all instances
of $(D lPar) are closed by corresponding instances of $(D rPar). The of `lPar` are closed by corresponding instances of `rPar`. The
parameter $(D maxNestingLevel) controls the nesting level allowed. The parameter `maxNestingLevel` controls the nesting level allowed. The
most common uses are the default or $(D 0). In the latter case, no most common uses are the default or `0`. In the latter case, no
nesting is allowed. nesting is allowed.
Params: Params:
@ -263,18 +263,18 @@ if (isInputRange!(Range) && is(typeof(r.front == lPar)))
} }
/** /**
* Sets up Boyer-Moore matching for use with $(D find) below. * Sets up Boyer-Moore matching for use with `find` below.
* By default, elements are compared for equality. * By default, elements are compared for equality.
* *
* $(D BoyerMooreFinder) allocates GC memory. * `BoyerMooreFinder` allocates GC memory.
* *
* Params: * Params:
* pred = Predicate used to compare elements. * pred = Predicate used to compare elements.
* needle = A random-access range with length and slicing. * needle = A random-access range with length and slicing.
* *
* Returns: * Returns:
* An instance of $(D BoyerMooreFinder) that can be used with $(D find()) to * An instance of `BoyerMooreFinder` that can be used with `find()` to
* invoke the Boyer-Moore matching algorithm for finding of $(D needle) in a * invoke the Boyer-Moore matching algorithm for finding of `needle` in a
* given haystack. * given haystack.
*/ */
struct BoyerMooreFinder(alias pred, Range) struct BoyerMooreFinder(alias pred, Range)
@ -407,7 +407,7 @@ Returns the common prefix of two ranges.
Params: Params:
pred = The predicate to use in comparing elements for commonality. Defaults pred = The predicate to use in comparing elements for commonality. Defaults
to equality $(D "a == b"). to equality `"a == b"`.
r1 = A $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) of r1 = A $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) of
elements. elements.
@ -416,9 +416,9 @@ Params:
elements. elements.
Returns: Returns:
A slice of $(D r1) which contains the characters that both ranges start with, A slice of `r1` which contains the characters that both ranges start with,
if the first argument is a string; otherwise, the same as the result of if the first argument is a string; otherwise, the same as the result of
$(D takeExactly(r1, n)), where $(D n) is the number of elements in the common `takeExactly(r1, n)`, where `n` is the number of elements in the common
prefix of both ranges. prefix of both ranges.
See_Also: See_Also:
@ -591,26 +591,26 @@ if (isNarrowString!R1 && isNarrowString!R2)
// count // count
/** /**
The first version counts the number of elements $(D x) in $(D r) for The first version counts the number of elements `x` in `r` for
which $(D pred(x, value)) is $(D true). $(D pred) defaults to which `pred(x, value)` is `true`. `pred` defaults to
equality. Performs $(BIGOH haystack.length) evaluations of $(D pred). equality. Performs $(BIGOH haystack.length) evaluations of `pred`.
The second version returns the number of times $(D needle) occurs in The second version returns the number of times `needle` occurs in
$(D haystack). Throws an exception if $(D needle.empty), as the _count `haystack`. Throws an exception if `needle.empty`, as the _count
of the empty range in any range would be infinite. Overlapped counts of the empty range in any range would be infinite. Overlapped counts
are not considered, for example $(D count("aaa", "aa")) is $(D 1), not are not considered, for example `count("aaa", "aa")` is `1`, not
$(D 2). `2`.
The third version counts the elements for which $(D pred(x)) is $(D The third version counts the elements for which `pred(x)` is $(D
true). Performs $(BIGOH haystack.length) evaluations of $(D pred). true). Performs $(BIGOH haystack.length) evaluations of `pred`.
The fourth version counts the number of elements in a range. It is The fourth version counts the number of elements in a range. It is
an optimization for the third version: if the given range has the an optimization for the third version: if the given range has the
`length` property the count is returned right away, otherwise `length` property the count is returned right away, otherwise
performs $(BIGOH haystack.length) to walk the range. performs $(BIGOH haystack.length) to walk the range.
Note: Regardless of the overload, $(D count) will not accept Note: Regardless of the overload, `count` will not accept
infinite ranges for $(D haystack). infinite ranges for `haystack`.
Params: Params:
pred = The predicate to evaluate. pred = The predicate to evaluate.
@ -732,7 +732,7 @@ if (isInputRange!R && !isInfinite!R)
/++ /++
Counts elements in the given Counts elements in the given
$(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
until the given predicate is true for one of the given $(D needles). until the given predicate is true for one of the given `needles`.
Params: Params:
pred = The predicate for determining when to stop counting. pred = The predicate for determining when to stop counting.
@ -742,13 +742,13 @@ if (isInputRange!R && !isInfinite!R)
needles = Either a single element, or a needles = Either a single element, or a
$(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
of elements, to be evaluated in turn against each of elements, to be evaluated in turn against each
element in $(D haystack) under the given predicate. element in `haystack` under the given predicate.
Returns: The number of elements which must be popped from the front of Returns: The number of elements which must be popped from the front of
$(D haystack) before reaching an element for which `haystack` before reaching an element for which
$(D startsWith!pred(haystack, needles)) is $(D true). If `startsWith!pred(haystack, needles)` is `true`. If
$(D startsWith!pred(haystack, needles)) is not $(D true) for any element in `startsWith!pred(haystack, needles)` is not `true` for any element in
$(D haystack), then $(D -1) is returned. `haystack`, then `-1` is returned.
See_Also: $(REF indexOf, std,string) See_Also: $(REF indexOf, std,string)
+/ +/
@ -899,16 +899,16 @@ if (isInputRange!R &&
} }
/++ /++
Similar to the previous overload of $(D countUntil), except that this one Similar to the previous overload of `countUntil`, except that this one
evaluates only the predicate $(D pred). evaluates only the predicate `pred`.
Params: Params:
pred = Predicate to when to stop counting. pred = Predicate to when to stop counting.
haystack = An haystack = An
$(REF_ALTTEXT input range, isInputRange, std,range,primitives) of $(REF_ALTTEXT input range, isInputRange, std,range,primitives) of
elements to be counted. elements to be counted.
Returns: The number of elements which must be popped from $(D haystack) Returns: The number of elements which must be popped from `haystack`
before $(D pred(haystack.front)) is $(D true). before `pred(haystack.front)` is `true`.
+/ +/
ptrdiff_t countUntil(alias pred, R)(R haystack) ptrdiff_t countUntil(alias pred, R)(R haystack)
if (isInputRange!R && if (isInputRange!R &&
@ -995,7 +995,7 @@ if (isInputRange!R &&
/** /**
Checks if the given range ends with (one of) the given needle(s). Checks if the given range ends with (one of) the given needle(s).
The reciprocal of $(D startsWith). The reciprocal of `startsWith`.
Params: Params:
pred = The predicate to use for comparing elements between the range and pred = The predicate to use for comparing elements between the range and
@ -1013,11 +1013,11 @@ Params:
Returns: Returns:
0 if the needle(s) do not occur at the end of the given range; 0 if the needle(s) do not occur at the end of the given range;
otherwise the position of the matching needle, that is, 1 if the range ends otherwise the position of the matching needle, that is, 1 if the range ends
with $(D withOneOfThese[0]), 2 if it ends with $(D withOneOfThese[1]), and so with `withOneOfThese[0]`, 2 if it ends with `withOneOfThese[1]`, and so
on. on.
In the case when no needle parameters are given, return $(D true) iff back of In the case when no needle parameters are given, return `true` iff back of
$(D doesThisStart) fulfils predicate $(D pred). `doesThisStart` fulfils predicate `pred`.
*/ */
uint endsWith(alias pred = "a == b", Range, Needles...)(Range doesThisEnd, Needles withOneOfThese) uint endsWith(alias pred = "a == b", Range, Needles...)(Range doesThisEnd, Needles withOneOfThese)
if (isBidirectionalRange!Range && Needles.length > 1 && if (isBidirectionalRange!Range && Needles.length > 1 &&
@ -1458,18 +1458,18 @@ private auto extremum(alias selector = "a < b", Range,
// find // find
/** /**
Finds an individual element in an input range. Elements of $(D Finds an individual element in an input range. Elements of $(D
haystack) are compared with $(D needle) by using predicate $(D haystack) are compared with `needle` by using predicate $(D
pred). Performs $(BIGOH walkLength(haystack)) evaluations of $(D pred). Performs $(BIGOH walkLength(haystack)) evaluations of $(D
pred). pred).
To _find the last occurrence of $(D needle) in $(D haystack), call $(D To _find the last occurrence of `needle` in `haystack`, call $(D
find(retro(haystack), needle)). See $(REF retro, std,range). find(retro(haystack), needle)). See $(REF retro, std,range).
Params: Params:
pred = The predicate for comparing each element with the needle, defaulting to pred = The predicate for comparing each element with the needle, defaulting to
$(D "a == b"). `"a == b"`.
The negated predicate $(D "a != b") can be used to search instead for the first The negated predicate `"a != b"` can be used to search instead for the first
element $(I not) matching the needle. element $(I not) matching the needle.
haystack = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) haystack = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
@ -1477,16 +1477,11 @@ searched in.
needle = The element searched for. needle = The element searched for.
Constraints:
$(D isInputRange!InputRange && is(typeof(binaryFun!pred(haystack.front, needle)
: bool)))
Returns: Returns:
$(D haystack) advanced such that the front element is the one searched for; `haystack` advanced such that the front element is the one searched for;
that is, until $(D binaryFun!pred(haystack.front, needle)) is $(D true). If no that is, until `binaryFun!pred(haystack.front, needle)` is `true`. If no
such position exists, returns an empty $(D haystack). such position exists, returns an empty `haystack`.
See_Also: See_Also:
$(HTTP sgi.com/tech/stl/_find.html, STL's _find) $(HTTP sgi.com/tech/stl/_find.html, STL's _find)
@ -1766,14 +1761,14 @@ if (isInputRange!InputRange &&
} }
/** /**
Advances the input range $(D haystack) by calling $(D haystack.popFront) Advances the input range `haystack` by calling `haystack.popFront`
until either $(D pred(haystack.front)), or $(D until either `pred(haystack.front)`, or $(D
haystack.empty). Performs $(BIGOH haystack.length) evaluations of $(D haystack.empty). Performs $(BIGOH haystack.length) evaluations of $(D
pred). pred).
To _find the last element of a To _find the last element of a
$(REF_ALTTEXT bidirectional, isBidirectionalRange, std,range,primitives) $(D haystack) satisfying $(REF_ALTTEXT bidirectional, isBidirectionalRange, std,range,primitives) `haystack` satisfying
$(D pred), call $(D find!(pred)(retro(haystack))). See $(REF retro, std,range). `pred`, call `find!(pred)(retro(haystack))`. See $(REF retro, std,range).
`find` behaves similar to `dropWhile` in other languages. `find` behaves similar to `dropWhile` in other languages.
@ -1787,9 +1782,9 @@ search in.
Returns: Returns:
$(D haystack) advanced such that the front element is the one searched for; `haystack` advanced such that the front element is the one searched for;
that is, until $(D binaryFun!pred(haystack.front, needle)) is $(D true). If no that is, until `binaryFun!pred(haystack.front, needle)` is `true`. If no
such position exists, returns an empty $(D haystack). such position exists, returns an empty `haystack`.
See_Also: See_Also:
$(HTTP sgi.com/tech/stl/find_if.html, STL's find_if) $(HTTP sgi.com/tech/stl/find_if.html, STL's find_if)
@ -1859,7 +1854,7 @@ of the two ranges' content.
Params: Params:
pred = The predicate to use for comparing respective elements from the haystack pred = The predicate to use for comparing respective elements from the haystack
and the needle. Defaults to simple equality $(D "a == b"). and the needle. Defaults to simple equality `"a == b"`.
haystack = The $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) haystack = The $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
searched in. searched in.
@ -1869,8 +1864,8 @@ searched for.
Returns: Returns:
$(D haystack) advanced such that $(D needle) is a prefix of it (if no `haystack` advanced such that `needle` is a prefix of it (if no
such position exists, returns $(D haystack) advanced to termination). such position exists, returns `haystack` advanced to termination).
*/ */
R1 find(alias pred = "a == b", R1, R2)(R1 haystack, scope R2 needle) R1 find(alias pred = "a == b", R1, R2)(R1 haystack, scope R2 needle)
if (isForwardRange!R1 && isForwardRange!R2 if (isForwardRange!R1 && isForwardRange!R2
@ -2279,7 +2274,7 @@ private R1 simpleMindedFind(alias pred, R1, R2)(R1 haystack, scope R2 needle)
} }
/** /**
Finds two or more $(D needles) into a $(D haystack). The predicate $(D Finds two or more `needles` into a `haystack`. The predicate $(D
pred) is used throughout to compare elements. By default, elements are pred) is used throughout to compare elements. By default, elements are
compared for equality. compared for equality.
@ -2288,41 +2283,41 @@ Params:
pred = The predicate to use for comparing elements. pred = The predicate to use for comparing elements.
haystack = The target of the search. Must be an input range. haystack = The target of the search. Must be an input range.
If any of $(D needles) is a range with elements comparable to If any of `needles` is a range with elements comparable to
elements in $(D haystack), then $(D haystack) must be a elements in `haystack`, then `haystack` must be a
$(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
such that the search can backtrack. such that the search can backtrack.
needles = One or more items to search for. Each of $(D needles) must needles = One or more items to search for. Each of `needles` must
be either comparable to one element in $(D haystack), or be itself a be either comparable to one element in `haystack`, or be itself a
forward range with elements comparable with elements in forward range with elements comparable with elements in
$(D haystack). `haystack`.
Returns: Returns:
A tuple containing $(D haystack) positioned to match one of the A tuple containing `haystack` positioned to match one of the
needles and also the 1-based index of the matching element in $(D needles and also the 1-based index of the matching element in $(D
needles) (0 if none of $(D needles) matched, 1 if $(D needles[0]) needles) (0 if none of `needles` matched, 1 if `needles[0]`
matched, 2 if $(D needles[1]) matched...). The first needle to be found matched, 2 if `needles[1]` matched...). The first needle to be found
will be the one that matches. If multiple needles are found at the will be the one that matches. If multiple needles are found at the
same spot in the range, then the shortest one is the one which matches same spot in the range, then the shortest one is the one which matches
(if multiple needles of the same length are found at the same spot (e.g (if multiple needles of the same length are found at the same spot (e.g
$(D "a") and $(D 'a')), then the left-most of them in the argument list `"a"` and `'a'`), then the left-most of them in the argument list
matches). matches).
The relationship between $(D haystack) and $(D needles) simply means The relationship between `haystack` and `needles` simply means
that one can e.g. search for individual $(D int)s or arrays of $(D that one can e.g. search for individual `int`s or arrays of $(D
int)s in an array of $(D int)s. In addition, if elements are int)s in an array of `int`s. In addition, if elements are
individually comparable, searches of heterogeneous types are allowed individually comparable, searches of heterogeneous types are allowed
as well: a $(D double[]) can be searched for an $(D int) or a $(D as well: a `double[]` can be searched for an `int` or a $(D
short[]), and conversely a $(D long) can be searched for a $(D float) short[]), and conversely a `long` can be searched for a `float`
or a $(D double[]). This makes for efficient searches without the need or a `double[]`. This makes for efficient searches without the need
to coerce one side of the comparison into the other's side type. to coerce one side of the comparison into the other's side type.
The complexity of the search is $(BIGOH haystack.length * The complexity of the search is $(BIGOH haystack.length *
max(needles.length)). (For needles that are individual items, length max(needles.length)). (For needles that are individual items, length
is considered to be 1.) The strategy used in searching several is considered to be 1.) The strategy used in searching several
subranges at once maximizes cache usage by moving in $(D haystack) as subranges at once maximizes cache usage by moving in `haystack` as
few times as possible. few times as possible.
*/ */
Tuple!(Range, size_t) find(alias pred = "a == b", Range, Ranges...) Tuple!(Range, size_t) find(alias pred = "a == b", Range, Ranges...)
@ -2428,7 +2423,7 @@ if (Ranges.length > 1 && is(typeof(startsWith!pred(haystack, needles))))
} }
/** /**
* Finds $(D needle) in $(D haystack) efficiently using the * Finds `needle` in `haystack` efficiently using the
* $(LINK2 https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm, * $(LINK2 https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm,
* Boyer-Moore) method. * Boyer-Moore) method.
* *
@ -2437,8 +2432,8 @@ if (Ranges.length > 1 && is(typeof(startsWith!pred(haystack, needles))))
* needle = A $(LREF BoyerMooreFinder). * needle = A $(LREF BoyerMooreFinder).
* *
* Returns: * Returns:
* $(D haystack) advanced such that $(D needle) is a prefix of it (if no * `haystack` advanced such that `needle` is a prefix of it (if no
* such position exists, returns $(D haystack) advanced to termination). * such position exists, returns `haystack` advanced to termination).
*/ */
RandomAccessRange find(RandomAccessRange, alias pred, InputRange)( RandomAccessRange find(RandomAccessRange, alias pred, InputRange)(
RandomAccessRange haystack, scope BoyerMooreFinder!(pred, InputRange) needle) RandomAccessRange haystack, scope BoyerMooreFinder!(pred, InputRange) needle)
@ -2490,9 +2485,9 @@ template canFind(alias pred="a == b")
import std.meta : allSatisfy; import std.meta : allSatisfy;
/++ /++
Returns $(D true) if and only if any value $(D v) found in the Returns `true` if and only if any value `v` found in the
input range $(D range) satisfies the predicate $(D pred). input range `range` satisfies the predicate `pred`.
Performs (at most) $(BIGOH haystack.length) evaluations of $(D pred). Performs (at most) $(BIGOH haystack.length) evaluations of `pred`.
+/ +/
bool canFind(Range)(Range haystack) bool canFind(Range)(Range haystack)
if (is(typeof(find!pred(haystack)))) if (is(typeof(find!pred(haystack))))
@ -2501,8 +2496,8 @@ template canFind(alias pred="a == b")
} }
/++ /++
Returns $(D true) if and only if $(D needle) can be found in $(D Returns `true` if and only if `needle` can be found in $(D
range). Performs $(BIGOH haystack.length) evaluations of $(D pred). range). Performs $(BIGOH haystack.length) evaluations of `pred`.
+/ +/
bool canFind(Range, Element)(Range haystack, scope Element needle) bool canFind(Range, Element)(Range haystack, scope Element needle)
if (is(typeof(find!pred(haystack, needle)))) if (is(typeof(find!pred(haystack, needle))))
@ -2511,14 +2506,14 @@ template canFind(alias pred="a == b")
} }
/++ /++
Returns the 1-based index of the first needle found in $(D haystack). If no Returns the 1-based index of the first needle found in `haystack`. If no
needle is found, then $(D 0) is returned. needle is found, then `0` is returned.
So, if used directly in the condition of an if statement or loop, the result So, if used directly in the condition of an if statement or loop, the result
will be $(D true) if one of the needles is found and $(D false) if none are will be `true` if one of the needles is found and `false` if none are
found, whereas if the result is used elsewhere, it can either be cast to found, whereas if the result is used elsewhere, it can either be cast to
$(D bool) for the same effect or used to get which needle was found first `bool` for the same effect or used to get which needle was found first
without having to deal with the tuple that $(D LREF find) returns for the without having to deal with the tuple that `LREF find` returns for the
same operation. same operation.
+/ +/
size_t canFind(Range, Ranges...)(Range haystack, scope Ranges needles) size_t canFind(Range, Ranges...)(Range haystack, scope Ranges needles)
@ -2579,9 +2574,9 @@ template canFind(alias pred="a == b")
// findAdjacent // findAdjacent
/** /**
Advances $(D r) until it finds the first two adjacent elements $(D a), Advances `r` until it finds the first two adjacent elements `a`,
$(D b) that satisfy $(D pred(a, b)). Performs $(BIGOH r.length) `b` that satisfy `pred(a, b)`. Performs $(BIGOH r.length)
evaluations of $(D pred). evaluations of `pred`.
Params: Params:
pred = The predicate to satisfy. pred = The predicate to satisfy.
@ -2589,8 +2584,8 @@ Params:
search in. search in.
Returns: Returns:
$(D r) advanced to the first occurrence of two adjacent elements that satisfy `r` advanced to the first occurrence of two adjacent elements that satisfy
the given predicate. If there are no such two elements, returns $(D r) advanced the given predicate. If there are no such two elements, returns `r` advanced
until empty. until empty.
See_Also: See_Also:
@ -2654,9 +2649,9 @@ if (isForwardRange!(Range))
/** /**
Searches the given range for an element that matches one of the given choices. Searches the given range for an element that matches one of the given choices.
Advances $(D seq) by calling $(D seq.popFront) until either Advances `seq` by calling `seq.popFront` until either
$(D find!(pred)(choices, seq.front)) is $(D true), or $(D seq) becomes empty. `find!(pred)(choices, seq.front)` is `true`, or `seq` becomes empty.
Performs $(BIGOH seq.length * choices.length) evaluations of $(D pred). Performs $(BIGOH seq.length * choices.length) evaluations of `pred`.
Params: Params:
pred = The predicate to use for determining a match. pred = The predicate to use for determining a match.
@ -2666,7 +2661,7 @@ Params:
of possible choices. of possible choices.
Returns: Returns:
$(D seq) advanced to the first matching element, or until empty if there are no `seq` advanced to the first matching element, or until empty if there are no
matching elements. matching elements.
See_Also: See_Also:
@ -2702,8 +2697,8 @@ if (isInputRange!InputRange && isForwardRange!ForwardRange)
// findSkip // findSkip
/** /**
* Finds $(D needle) in $(D haystack) and positions $(D haystack) * Finds `needle` in `haystack` and positions `haystack`
* right after the first occurrence of $(D needle). * right after the first occurrence of `needle`.
* *
* Params: * Params:
* haystack = The * haystack = The
@ -2714,9 +2709,9 @@ if (isInputRange!InputRange && isForwardRange!ForwardRange)
* for. * for.
* pred = Custom predicate for comparison of haystack and needle * pred = Custom predicate for comparison of haystack and needle
* *
* Returns: $(D true) if the needle was found, in which case $(D haystack) is * Returns: `true` if the needle was found, in which case `haystack` is
* positioned after the end of the first occurrence of $(D needle); otherwise * positioned after the end of the first occurrence of `needle`; otherwise
* $(D false), leaving $(D haystack) untouched. * `false`, leaving `haystack` untouched.
*/ */
bool findSkip(alias pred = "a == b", R1, R2)(ref R1 haystack, R2 needle) bool findSkip(alias pred = "a == b", R1, R2)(ref R1 haystack, R2 needle)
if (isForwardRange!R1 && isForwardRange!R2 if (isForwardRange!R1 && isForwardRange!R2
@ -3177,16 +3172,16 @@ if (isForwardRange!R1 && isForwardRange!R2)
Computes the minimum (respectively maximum) of `range` along with its number of Computes the minimum (respectively maximum) of `range` along with its number of
occurrences. Formally, the minimum is a value `x` in `range` such that $(D occurrences. Formally, the minimum is a value `x` in `range` such that $(D
pred(a, x)) is `false` for all values `a` in `range`. Conversely, the maximum is pred(a, x)) is `false` for all values `a` in `range`. Conversely, the maximum is
a value `x` in `range` such that $(D pred(x, a)) is `false` for all values `a` a value `x` in `range` such that `pred(x, a)` is `false` for all values `a`
in `range` (note the swapped arguments to `pred`). in `range` (note the swapped arguments to `pred`).
These functions may be used for computing arbitrary extrema by choosing `pred` These functions may be used for computing arbitrary extrema by choosing `pred`
appropriately. For corrrect functioning, `pred` must be a strict partial order, appropriately. For corrrect functioning, `pred` must be a strict partial order,
i.e. transitive (if $(D pred(a, b) && pred(b, c)) then $(D pred(a, c))) and i.e. transitive (if `pred(a, b) && pred(b, c)` then `pred(a, c)`) and
irreflexive ($(D pred(a, a)) is `false`). The $(LUCKY trichotomy property of irreflexive (`pred(a, a)` is `false`). The $(LUCKY trichotomy property of
inequality) is not required: these algoritms consider elements `a` and `b` equal inequality) is not required: these algoritms consider elements `a` and `b` equal
(for the purpose of counting) if `pred` puts them in the same equivalence class, (for the purpose of counting) if `pred` puts them in the same equivalence class,
i.e. $(D !pred(a, b) && !pred(b, a)). i.e. `!pred(a, b) && !pred(b, a)`.
Params: Params:
pred = The ordering predicate to use to determine the extremum (minimum pred = The ordering predicate to use to determine the extremum (minimum
@ -3623,15 +3618,15 @@ Computes a subrange of `range` starting at the first occurrence of `range`'s
minimum (respectively maximum) and with the same ending as `range`, or the minimum (respectively maximum) and with the same ending as `range`, or the
empty range if `range` itself is empty. empty range if `range` itself is empty.
Formally, the minimum is a value `x` in `range` such that $(D pred(a, x)) is Formally, the minimum is a value `x` in `range` such that `pred(a, x)` is
`false` for all values `a` in `range`. Conversely, the maximum is a value `x` in `false` for all values `a` in `range`. Conversely, the maximum is a value `x` in
`range` such that $(D pred(x, a)) is `false` for all values `a` in `range` (note `range` such that `pred(x, a)` is `false` for all values `a` in `range` (note
the swapped arguments to `pred`). the swapped arguments to `pred`).
These functions may be used for computing arbitrary extrema by choosing `pred` These functions may be used for computing arbitrary extrema by choosing `pred`
appropriately. For corrrect functioning, `pred` must be a strict partial order, appropriately. For corrrect functioning, `pred` must be a strict partial order,
i.e. transitive (if $(D pred(a, b) && pred(b, c)) then $(D pred(a, c))) and i.e. transitive (if `pred(a, b) && pred(b, c)` then `pred(a, c)`) and
irreflexive ($(D pred(a, a)) is `false`). irreflexive (`pred(a, a)` is `false`).
Params: Params:
pred = The ordering predicate to use to determine the extremum (minimum or pred = The ordering predicate to use to determine the extremum (minimum or
@ -3950,7 +3945,7 @@ Do nothing if there is no match.
Params: Params:
pred = The predicate that determines whether elements from each respective pred = The predicate that determines whether elements from each respective
range match. Defaults to equality $(D "a == b"). range match. Defaults to equality `"a == b"`.
*/ */
template skipOver(alias pred = "a == b") template skipOver(alias pred = "a == b")
{ {
@ -3958,13 +3953,13 @@ template skipOver(alias pred = "a == b")
r1 = The $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) to r1 = The $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) to
move forward. move forward.
r2 = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives) r2 = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
representing the initial segment of $(D r1) to skip over. representing the initial segment of `r1` to skip over.
e = The element to match. e = The element to match.
Returns: Returns:
true if the initial segment of $(D r1) matches $(D r2) or $(D pred) evaluates to true, true if the initial segment of `r1` matches `r2` or `pred` evaluates to true,
and $(D r1) has been advanced to the point past this segment; otherwise false, and and `r1` has been advanced to the point past this segment; otherwise false, and
$(D r1) is left in its original position. `r1` is left in its original position.
*/ */
bool skipOver(R1, R2)(ref R1 r1, R2 r2) bool skipOver(R1, R2)(ref R1 r1, R2 r2)
if (is(typeof(binaryFun!pred(r1.front, r2.front))) && if (is(typeof(binaryFun!pred(r1.front, r2.front))) &&
@ -4097,7 +4092,7 @@ template skipOver(alias pred = "a == b")
Checks whether the given Checks whether the given
$(REF_ALTTEXT input range, isInputRange, std,range,primitives) starts with (one $(REF_ALTTEXT input range, isInputRange, std,range,primitives) starts with (one
of) the given needle(s) or, if no needles are given, of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate $(D pred). if its front element fulfils predicate `pred`.
Params: Params:
@ -4116,17 +4111,17 @@ Returns:
0 if the needle(s) do not occur at the beginning of the given range; 0 if the needle(s) do not occur at the beginning of the given range;
otherwise the position of the matching needle, that is, 1 if the range starts otherwise the position of the matching needle, that is, 1 if the range starts
with $(D withOneOfThese[0]), 2 if it starts with $(D withOneOfThese[1]), and so with `withOneOfThese[0]`, 2 if it starts with `withOneOfThese[1]`, and so
on. on.
In the case where $(D doesThisStart) starts with multiple of the ranges or In the case where `doesThisStart` starts with multiple of the ranges or
elements in $(D withOneOfThese), then the shortest one matches (if there are elements in `withOneOfThese`, then the shortest one matches (if there are
two which match which are of the same length (e.g. $(D "a") and $(D 'a')), then two which match which are of the same length (e.g. `"a"` and `'a'`), then
the left-most of them in the argument the left-most of them in the argument
list matches). list matches).
In the case when no needle parameters are given, return $(D true) iff front of In the case when no needle parameters are given, return `true` iff front of
$(D doesThisStart) fulfils predicate $(D pred). `doesThisStart` fulfils predicate `pred`.
*/ */
uint startsWith(alias pred = "a == b", Range, Needles...)(Range doesThisStart, Needles withOneOfThese) uint startsWith(alias pred = "a == b", Range, Needles...)(Range doesThisStart, Needles withOneOfThese)
if (isInputRange!Range && Needles.length > 1 && if (isInputRange!Range && Needles.length > 1 &&
@ -4427,8 +4422,8 @@ if (isInputRange!R &&
} }
/* (Not yet documented.) /* (Not yet documented.)
Consume all elements from $(D r) that are equal to one of the elements Consume all elements from `r` that are equal to one of the elements
$(D es). `es`.
*/ */
private void skipAll(alias pred = "a == b", R, Es...)(ref R r, Es es) private void skipAll(alias pred = "a == b", R, Es...)(ref R r, Es es)
//if (is(typeof(binaryFun!pred(r1.front, es[0])))) //if (is(typeof(binaryFun!pred(r1.front, es[0]))))
@ -4457,17 +4452,17 @@ private void skipAll(alias pred = "a == b", R, Es...)(ref R r, Es es)
/** /**
Interval option specifier for `until` (below) and others. Interval option specifier for `until` (below) and others.
If set to $(D OpenRight.yes), then the interval is open to the right If set to `OpenRight.yes`, then the interval is open to the right
(last element is not included). (last element is not included).
Otherwise if set to $(D OpenRight.no), then the interval is closed to the right Otherwise if set to `OpenRight.no`, then the interval is closed to the right
(last element included). (last element included).
*/ */
alias OpenRight = Flag!"openRight"; alias OpenRight = Flag!"openRight";
/** /**
Lazily iterates $(D range) _until the element $(D e) for which Lazily iterates `range` _until the element `e` for which
$(D pred(e, sentinel)) is true. `pred(e, sentinel)` is true.
This is similar to `takeWhile` in other languages. This is similar to `takeWhile` in other languages.
@ -4477,8 +4472,8 @@ Params:
to iterate over. to iterate over.
sentinel = The element to stop at. sentinel = The element to stop at.
openRight = Determines whether the element for which the given predicate is openRight = Determines whether the element for which the given predicate is
true should be included in the resulting range ($(D No.openRight)), or true should be included in the resulting range (`No.openRight`), or
not ($(D Yes.openRight)). not (`Yes.openRight`).
Returns: Returns:
An $(REF_ALTTEXT input _range, isInputRange, std,_range,primitives) that An $(REF_ALTTEXT input _range, isInputRange, std,_range,primitives) that

View file

@ -557,9 +557,9 @@ pure @safe nothrow @nogc unittest
// largestPartialIntersection // largestPartialIntersection
/** /**
Given a range of sorted $(REF_ALTTEXT forward ranges, isForwardRange, std,range,primitives) Given a range of sorted $(REF_ALTTEXT forward ranges, isForwardRange, std,range,primitives)
$(D ror), copies to $(D tgt) the elements that are common to most ranges, along with their number `ror`, copies to `tgt` the elements that are common to most ranges, along with their number
of occurrences. All ranges in $(D ror) are assumed to be sorted by $(D of occurrences. All ranges in `ror` are assumed to be sorted by $(D
less). Only the most frequent $(D tgt.length) elements are returned. less). Only the most frequent `tgt.length` elements are returned.
Params: Params:
less = The predicate the ranges are sorted by. less = The predicate the ranges are sorted by.
@ -567,27 +567,27 @@ Params:
tgt = The target range to copy common elements to. tgt = The target range to copy common elements to.
sorted = Whether the elements copied should be in sorted order. sorted = Whether the elements copied should be in sorted order.
The function $(D largestPartialIntersection) is useful for The function `largestPartialIntersection` is useful for
e.g. searching an $(LINK2 https://en.wikipedia.org/wiki/Inverted_index, e.g. searching an $(LINK2 https://en.wikipedia.org/wiki/Inverted_index,
inverted index) for the documents most inverted index) for the documents most
likely to contain some terms of interest. The complexity of the search likely to contain some terms of interest. The complexity of the search
is $(BIGOH n * log(tgt.length)), where $(D n) is the sum of lengths of is $(BIGOH n * log(tgt.length)), where `n` is the sum of lengths of
all input ranges. This approach is faster than keeping an associative all input ranges. This approach is faster than keeping an associative
array of the occurrences and then selecting its top items, and also array of the occurrences and then selecting its top items, and also
requires less memory ($(D largestPartialIntersection) builds its requires less memory (`largestPartialIntersection` builds its
result directly in $(D tgt) and requires no extra memory). result directly in `tgt` and requires no extra memory).
If at least one of the ranges is a multiset, then all occurences If at least one of the ranges is a multiset, then all occurences
of a duplicate element are taken into account. The result is of a duplicate element are taken into account. The result is
equivalent to merging all ranges and picking the most frequent equivalent to merging all ranges and picking the most frequent
$(D tgt.length) elements. `tgt.length` elements.
Warning: Because $(D largestPartialIntersection) does not allocate Warning: Because `largestPartialIntersection` does not allocate
extra memory, it will leave $(D ror) modified. Namely, $(D extra memory, it will leave `ror` modified. Namely, $(D
largestPartialIntersection) assumes ownership of $(D ror) and largestPartialIntersection) assumes ownership of `ror` and
discretionarily swaps and advances elements of it. If you want $(D discretionarily swaps and advances elements of it. If you want $(D
ror) to preserve its contents after the call, you may want to pass a ror) to preserve its contents after the call, you may want to pass a
duplicate to $(D largestPartialIntersection) (and perhaps cache the duplicate to `largestPartialIntersection` (and perhaps cache the
duplicate in between calls). duplicate in between calls).
*/ */
void largestPartialIntersection void largestPartialIntersection
@ -652,13 +652,13 @@ import std.algorithm.sorting : SortOutput; // FIXME
// largestPartialIntersectionWeighted // largestPartialIntersectionWeighted
/** /**
Similar to $(D largestPartialIntersection), but associates a weight Similar to `largestPartialIntersection`, but associates a weight
with each distinct element in the intersection. with each distinct element in the intersection.
If at least one of the ranges is a multiset, then all occurences If at least one of the ranges is a multiset, then all occurences
of a duplicate element are taken into account. The result of a duplicate element are taken into account. The result
is equivalent to merging all input ranges and picking the highest is equivalent to merging all input ranges and picking the highest
$(D tgt.length), weight-based ranking elements. `tgt.length`, weight-based ranking elements.
Params: Params:
less = The predicate the ranges are sorted by. less = The predicate the ranges are sorted by.
@ -798,15 +798,15 @@ void largestPartialIntersectionWeighted
Merges multiple sets. The input sets are passed as a Merges multiple sets. The input sets are passed as a
range of ranges and each is assumed to be sorted by $(D range of ranges and each is assumed to be sorted by $(D
less). Computation is done lazily, one union element at a time. The less). Computation is done lazily, one union element at a time. The
complexity of one $(D popFront) operation is $(BIGOH complexity of one `popFront` operation is $(BIGOH
log(ror.length)). However, the length of $(D ror) decreases as ranges log(ror.length)). However, the length of `ror` decreases as ranges
in it are exhausted, so the complexity of a full pass through $(D in it are exhausted, so the complexity of a full pass through $(D
MultiwayMerge) is dependent on the distribution of the lengths of ranges MultiwayMerge) is dependent on the distribution of the lengths of ranges
contained within $(D ror). If all ranges have the same length $(D n) contained within `ror`. If all ranges have the same length `n`
(worst case scenario), the complexity of a full pass through $(D (worst case scenario), the complexity of a full pass through $(D
MultiwayMerge) is $(BIGOH n * ror.length * log(ror.length)), i.e., $(D MultiwayMerge) is $(BIGOH n * ror.length * log(ror.length)), i.e., $(D
log(ror.length)) times worse than just spanning all ranges in log(ror.length)) times worse than just spanning all ranges in
turn. The output comes sorted (unstably) by $(D less). turn. The output comes sorted (unstably) by `less`.
The length of the resulting range is the sum of all lengths of The length of the resulting range is the sum of all lengths of
the ranges passed as input. This means that all elements (duplicates the ranges passed as input. This means that all elements (duplicates
@ -824,11 +824,11 @@ Params:
Returns: Returns:
A range of the union of the ranges in `ror`. A range of the union of the ranges in `ror`.
Warning: Because $(D MultiwayMerge) does not allocate extra memory, it Warning: Because `MultiwayMerge` does not allocate extra memory, it
will leave $(D ror) modified. Namely, $(D MultiwayMerge) assumes ownership will leave `ror` modified. Namely, `MultiwayMerge` assumes ownership
of $(D ror) and discretionarily swaps and advances elements of it. If of `ror` and discretionarily swaps and advances elements of it. If
you want $(D ror) to preserve its contents after the call, you may you want `ror` to preserve its contents after the call, you may
want to pass a duplicate to $(D MultiwayMerge) (and perhaps cache the want to pass a duplicate to `MultiwayMerge` (and perhaps cache the
duplicate in between calls). duplicate in between calls).
*/ */
struct MultiwayMerge(alias less, RangeOfRanges) struct MultiwayMerge(alias less, RangeOfRanges)
@ -983,13 +983,13 @@ auto multiwayUnion(alias less = "a < b", RangeOfRanges)(RangeOfRanges ror)
} }
/** /**
Lazily computes the difference of $(D r1) and $(D r2). The two ranges Lazily computes the difference of `r1` and `r2`. The two ranges
are assumed to be sorted by $(D less). The element types of the two are assumed to be sorted by `less`. The element types of the two
ranges must have a common type. ranges must have a common type.
In the case of multisets, considering that element `a` appears `x` In the case of multisets, considering that element `a` appears `x`
times in $(D r1) and `y` times and $(D r2), the number of occurences times in `r1` and `y` times and `r2`, the number of occurences
of `a` in the resulting range is going to be `x-y` if x > y or 0 othwerise. of `a` in the resulting range is going to be `x-y` if x > y or 0 othwerise.
Params: Params:
@ -1108,7 +1108,7 @@ SetDifference!(less, R1, R2) setDifference(alias less = "a < b", R1, R2)
/** /**
Lazily computes the intersection of two or more input ranges $(D Lazily computes the intersection of two or more input ranges $(D
ranges). The ranges are assumed to be sorted by $(D less). The element ranges). The ranges are assumed to be sorted by `less`. The element
types of the ranges must have a common type. types of the ranges must have a common type.
In the case of multisets, the range with the minimum number of In the case of multisets, the range with the minimum number of
@ -1274,20 +1274,20 @@ if (Rs.length >= 2 && allSatisfy!(isInputRange, Rs) &&
} }
/** /**
Lazily computes the symmetric difference of $(D r1) and $(D r2), Lazily computes the symmetric difference of `r1` and `r2`,
i.e. the elements that are present in exactly one of $(D r1) and $(D i.e. the elements that are present in exactly one of `r1` and $(D
r2). The two ranges are assumed to be sorted by $(D less), and the r2). The two ranges are assumed to be sorted by `less`, and the
output is also sorted by $(D less). The element types of the two output is also sorted by `less`. The element types of the two
ranges must have a common type. ranges must have a common type.
If both ranges are sets (without duplicated elements), the resulting If both ranges are sets (without duplicated elements), the resulting
range is going to be a set. If at least one of the ranges is a multiset, range is going to be a set. If at least one of the ranges is a multiset,
the number of occurences of an element `x` in the resulting range is `abs(a-b)` the number of occurences of an element `x` in the resulting range is `abs(a-b)`
where `a` is the number of occurences of `x` in $(D r1), `b` is the number of where `a` is the number of occurences of `x` in `r1`, `b` is the number of
occurences of `x` in $(D r2), and `abs` is the absolute value. occurences of `x` in `r2`, and `abs` is the absolute value.
If both arguments are ranges of L-values of the same type then If both arguments are ranges of L-values of the same type then
$(D SetSymmetricDifference) will also be a range of L-values of `SetSymmetricDifference` will also be a range of L-values of
that type. that type.
Params: Params:
@ -1435,8 +1435,8 @@ TODO: once SetUnion got deprecated we can provide the usual definition
(= merge + filter after uniqs) (= merge + filter after uniqs)
See: https://github.com/dlang/phobos/pull/4249 See: https://github.com/dlang/phobos/pull/4249
/** /**
Lazily computes the union of two or more ranges $(D rs). The ranges Lazily computes the union of two or more ranges `rs`. The ranges
are assumed to be sorted by $(D less). Elements in the output are are assumed to be sorted by `less`. Elements in the output are
unique. The element types of all ranges must have a common type. unique. The element types of all ranges must have a common type.
Params: Params:

View file

@ -7,23 +7,23 @@ $(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE Cheat Sheet, $(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description)) $(TR $(TH Function Name) $(TH Description))
$(T2 completeSort, $(T2 completeSort,
If $(D a = [10, 20, 30]) and $(D b = [40, 6, 15]), then If `a = [10, 20, 30]` and `b = [40, 6, 15]`, then
$(D completeSort(a, b)) leaves $(D a = [6, 10, 15]) and $(D b = [20, `completeSort(a, b)` leaves `a = [6, 10, 15]` and `b = [20$D(
30, 40]). 30, 40]).
The range $(D a) must be sorted prior to the call, and as a result the The range `a` must be sorted prior to the call, and as a result the
combination $(D $(REF chain, std,range)(a, b)) is sorted.) combination `$(REF chain, std,range)(a, b)` is sorted.)
$(T2 isPartitioned, $(T2 isPartitioned,
$(D isPartitioned!"a < 0"([-1, -2, 1, 0, 2])) returns $(D true) because `isPartitioned!"a < 0"([-1, -2, 1, 0, 2])` returns `true` because
the predicate is $(D true) for a portion of the range and $(D false) the predicate is `true` for a portion of the range and `false`
afterwards.) afterwards.)
$(T2 isSorted, $(T2 isSorted,
$(D isSorted([1, 1, 2, 3])) returns $(D true).) `isSorted([1, 1, 2, 3])` returns `true`.)
$(T2 isStrictlyMonotonic, $(T2 isStrictlyMonotonic,
$(D isStrictlyMonotonic([1, 1, 2, 3])) returns $(D false).) `isStrictlyMonotonic([1, 1, 2, 3])` returns `false`.)
$(T2 ordered, $(T2 ordered,
$(D ordered(1, 1, 2, 3)) returns $(D true).) `ordered(1, 1, 2, 3)` returns `true`.)
$(T2 strictlyOrdered, $(T2 strictlyOrdered,
$(D strictlyOrdered(1, 1, 2, 3)) returns $(D false).) `strictlyOrdered(1, 1, 2, 3)` returns `false`.)
$(T2 makeIndex, $(T2 makeIndex,
Creates a separate index for a range.) Creates a separate index for a range.)
$(T2 merge, $(T2 merge,
@ -37,9 +37,9 @@ $(T2 nextPermutation,
Computes the next lexicographically greater permutation of a range Computes the next lexicographically greater permutation of a range
in-place.) in-place.)
$(T2 partialSort, $(T2 partialSort,
If $(D a = [5, 4, 3, 2, 1]), then $(D partialSort(a, 3)) leaves If `a = [5, 4, 3, 2, 1]`, then `partialSort(a, 3)` leaves
$(D a[0 .. 3] = [1, 2, 3]). `a[0 .. 3] = [1, 2, 3]`.
The other elements of $(D a) are left in an unspecified order.) The other elements of `a` are left in an unspecified order.)
$(T2 partition, $(T2 partition,
Partitions a range according to a unary predicate.) Partitions a range according to a unary predicate.)
$(T2 partition3, $(T2 partition3,
@ -88,21 +88,21 @@ import std.traits;
Specifies whether the output of certain algorithm is desired in sorted Specifies whether the output of certain algorithm is desired in sorted
format. format.
If set to $(D SortOutput.no), the output should not be sorted. If set to `SortOutput.no`, the output should not be sorted.
Otherwise if set to $(D SortOutput.yes), the output should be sorted. Otherwise if set to `SortOutput.yes`, the output should be sorted.
*/ */
alias SortOutput = Flag!"sortOutput"; alias SortOutput = Flag!"sortOutput";
// completeSort // completeSort
/** /**
Sorts the random-access range $(D chain(lhs, rhs)) according to Sorts the random-access range `chain(lhs, rhs)` according to
predicate $(D less). The left-hand side of the range $(D lhs) is predicate `less`. The left-hand side of the range `lhs` is
assumed to be already sorted; $(D rhs) is assumed to be unsorted. The assumed to be already sorted; `rhs` is assumed to be unsorted. The
exact strategy chosen depends on the relative sizes of $(D lhs) and exact strategy chosen depends on the relative sizes of `lhs` and
$(D rhs). Performs $(BIGOH lhs.length + rhs.length * log(rhs.length)) `rhs`. Performs $(BIGOH lhs.length + rhs.length * log(rhs.length))
(best case) to $(BIGOH (lhs.length + rhs.length) * log(lhs.length + (best case) to $(BIGOH (lhs.length + rhs.length) * log(lhs.length +
rhs.length)) (worst-case) evaluations of $(D swap). rhs.length)) (worst-case) evaluations of `swap`.
Params: Params:
less = The predicate to sort by. less = The predicate to sort by.
@ -143,8 +143,8 @@ if (hasLength!(RandomAccessRange2) && hasSlicing!(RandomAccessRange2))
// isSorted // isSorted
/** /**
Checks whether a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives) Checks whether a $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives)
is sorted according to the comparison operation $(D less). Performs $(BIGOH r.length) is sorted according to the comparison operation `less`. Performs $(BIGOH r.length)
evaluations of $(D less). evaluations of `less`.
Unlike `isSorted`, `isStrictlyMonotonic` does not allow for equal values, Unlike `isSorted`, `isStrictlyMonotonic` does not allow for equal values,
i.e. values for which both `less(a, b)` and `less(b, a)` are false. i.e. values for which both `less(a, b)` and `less(b, a)` are false.
@ -291,16 +291,16 @@ if (isForwardRange!Range)
} }
/** /**
Like $(D isSorted), returns $(D true) if the given $(D values) are ordered Like `isSorted`, returns `true` if the given `values` are ordered
according to the comparison operation $(D less). Unlike $(D isSorted), takes values according to the comparison operation `less`. Unlike `isSorted`, takes values
directly instead of structured in a range. directly instead of structured in a range.
$(D ordered) allows repeated values, e.g. $(D ordered(1, 1, 2)) is $(D true). To verify `ordered` allows repeated values, e.g. `ordered(1, 1, 2)` is `true`. To verify
that the values are ordered strictly monotonically, use $(D strictlyOrdered); that the values are ordered strictly monotonically, use `strictlyOrdered`;
$(D strictlyOrdered(1, 1, 2)) is $(D false). `strictlyOrdered(1, 1, 2)` is `false`.
With either function, the predicate must be a strict ordering. For example, With either function, the predicate must be a strict ordering. For example,
using $(D "a <= b") instead of $(D "a < b") is incorrect and will cause failed using `"a <= b"` instead of `"a < b"` is incorrect and will cause failed
assertions. assertions.
Params: Params:
@ -308,8 +308,8 @@ Params:
less = The comparison predicate less = The comparison predicate
Returns: Returns:
$(D true) if the values are ordered; $(D ordered) allows for duplicates, `true` if the values are ordered; `ordered` allows for duplicates,
$(D strictlyOrdered) does not. `strictlyOrdered` does not.
*/ */
bool ordered(alias less = "a < b", T...)(T values) bool ordered(alias less = "a < b", T...)(T values)
@ -366,15 +366,15 @@ if (is(typeof(ordered!less(values))))
// partition // partition
/** /**
Partitions a range in two using the given $(D predicate). Partitions a range in two using the given `predicate`.
Specifically, reorders the range $(D r = [left, right$(RPAREN)) using $(D swap) Specifically, reorders the range `r = [left, right$(RPAREN)` using `swap`
such that all elements $(D i) for which $(D predicate(i)) is $(D true) come such that all elements `i` for which `predicate(i)` is `true` come
before all elements $(D j) for which $(D predicate(j)) returns $(D false). before all elements `j` for which `predicate(j)` returns `false`.
Performs $(BIGOH r.length) (if unstable or semistable) or $(BIGOH Performs $(BIGOH r.length) (if unstable or semistable) or $(BIGOH
r.length * log(r.length)) (if stable) evaluations of $(D less) and $(D r.length * log(r.length)) (if stable) evaluations of `less` and $(D
swap). The unstable version computes the minimum possible evaluations swap). The unstable version computes the minimum possible evaluations
of $(D swap) (roughly half of those performed by the semistable of `swap` (roughly half of those performed by the semistable
version). version).
Params: Params:
@ -384,13 +384,13 @@ Params:
Returns: Returns:
The right part of $(D r) after partitioning. The right part of `r` after partitioning.
If $(D ss == SwapStrategy.stable), $(D partition) preserves the relative If `ss == SwapStrategy.stable`, `partition` preserves the relative
ordering of all elements $(D a), $(D b) in $(D r) for which $(D predicate(a) == ordering of all elements `a`, `b` in `r` for which `predicate(a) =$D(
predicate(b)). If $(D ss == SwapStrategy.semistable), $(D partition) preserves predicate(b)). If `ss == SwapStrategy.semistable`, `partition` preserves
the relative ordering of all elements $(D a), $(D b) in the left part of $(D r) the relative ordering of all elements `a`, `b` in the left part of `r`
for which $(D predicate(a) == predicate(b)). for which `predicate(a) == predicate(b)`.
See_Also: See_Also:
STL's $(HTTP sgi.com/tech/stl/_partition.html, _partition)$(BR) STL's $(HTTP sgi.com/tech/stl/_partition.html, _partition)$(BR)
@ -576,17 +576,17 @@ if (ss != SwapStrategy.stable && isInputRange!Range && hasSwappableElements!Rang
Partitions `r` around `pivot` using comparison function `less`, algorithm akin Partitions `r` around `pivot` using comparison function `less`, algorithm akin
to $(LINK2 https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme, to $(LINK2 https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme,
Hoare partition). Specifically, permutes elements of `r` and returns Hoare partition). Specifically, permutes elements of `r` and returns
an index $(D k < r.length) such that: an index `k < r.length` such that:
$(UL $(UL
$(LI `r[pivot]` is swapped to `r[k]`) $(LI `r[pivot]` is swapped to `r[k]`)
$(LI All elements `e` in subrange $(D r[0 .. k]) satisfy $(D !less(r[k], e)) $(LI All elements `e` in subrange `r[0 .. k]` satisfy `!less(r[k], e)`
(i.e. `r[k]` is greater than or equal to each element to its left according to (i.e. `r[k]` is greater than or equal to each element to its left according to
predicate `less`)) predicate `less`))
$(LI All elements `e` in subrange $(D r[0 .. k]) satisfy $(D !less(e, $(LI All elements `e` in subrange `r[0 .. k]` satisfy `!less(e$D(
r[k])) (i.e. `r[k]` is less than or equal to each element to its right r[k])) (i.e. `r[k]` is less than or equal to each element to its right
according to predicate `less`))) according to predicate `less`)))
@ -773,7 +773,7 @@ if (isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range)
Params: Params:
pred = The predicate that the range should be partitioned by. pred = The predicate that the range should be partitioned by.
r = The range to check. r = The range to check.
Returns: $(D true) if $(D r) is partitioned according to predicate $(D pred). Returns: `true` if `r` is partitioned according to predicate `pred`.
*/ */
bool isPartitioned(alias pred, Range)(Range r) bool isPartitioned(alias pred, Range)(Range r)
if (isForwardRange!(Range)) if (isForwardRange!(Range))
@ -799,13 +799,13 @@ if (isForwardRange!(Range))
// partition3 // partition3
/** /**
Rearranges elements in $(D r) in three adjacent ranges and returns Rearranges elements in `r` in three adjacent ranges and returns
them. The first and leftmost range only contains elements in $(D r) them. The first and leftmost range only contains elements in `r`
less than $(D pivot). The second and middle range only contains less than `pivot`. The second and middle range only contains
elements in $(D r) that are equal to $(D pivot). Finally, the third elements in `r` that are equal to `pivot`. Finally, the third
and rightmost range only contains elements in $(D r) that are greater and rightmost range only contains elements in `r` that are greater
than $(D pivot). The less-than test is defined by the binary function than `pivot`. The less-than test is defined by the binary function
$(D less). `less`.
Params: Params:
less = The predicate to use for the rearrangement. less = The predicate to use for the rearrangement.
@ -817,7 +817,7 @@ Returns:
A $(REF Tuple, std,typecons) of the three resulting ranges. These ranges are A $(REF Tuple, std,typecons) of the three resulting ranges. These ranges are
slices of the original range. slices of the original range.
BUGS: stable $(D partition3) has not been implemented yet. BUGS: stable `partition3` has not been implemented yet.
*/ */
auto partition3(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, E) auto partition3(alias less = "a < b", SwapStrategy ss = SwapStrategy.unstable, Range, E)
(Range r, E pivot) (Range r, E pivot)
@ -916,7 +916,7 @@ if (ss == SwapStrategy.unstable && isRandomAccessRange!Range
// makeIndex // makeIndex
/** /**
Computes an index for $(D r) based on the comparison $(D less). The Computes an index for `r` based on the comparison `less`. The
index is a sorted array of pointers or indices into the original index is a sorted array of pointers or indices into the original
range. This technique is similar to sorting, but it is more flexible range. This technique is similar to sorting, but it is more flexible
because (1) it allows "sorting" of immutable collections, (2) allows because (1) it allows "sorting" of immutable collections, (2) allows
@ -926,15 +926,15 @@ and (4) may be faster when dealing with large objects. However, using
an index may also be slower under certain circumstances due to the an index may also be slower under certain circumstances due to the
extra indirection, and is always larger than a sorting-based solution extra indirection, and is always larger than a sorting-based solution
because it needs space for the index in addition to the original because it needs space for the index in addition to the original
collection. The complexity is the same as $(D sort)'s. collection. The complexity is the same as `sort`'s.
The first overload of $(D makeIndex) writes to a range containing The first overload of `makeIndex` writes to a range containing
pointers, and the second writes to a range containing offsets. The pointers, and the second writes to a range containing offsets. The
first overload requires $(D Range) to be a first overload requires `Range` to be a
$(REF_ALTTEXT forward range, isForwardRange, std,range,primitives), and the $(REF_ALTTEXT forward range, isForwardRange, std,range,primitives), and the
latter requires it to be a random-access range. latter requires it to be a random-access range.
$(D makeIndex) overwrites its second argument with the result, but `makeIndex` overwrites its second argument with the result, but
never reallocates it. never reallocates it.
Params: Params:
@ -943,11 +943,11 @@ Params:
r = The range to index. r = The range to index.
index = The resulting index. index = The resulting index.
Returns: The pointer-based version returns a $(D SortedRange) wrapper Returns: The pointer-based version returns a `SortedRange` wrapper
over index, of type $(D SortedRange!(RangeIndex, (a, b) => over index, of type `SortedRange!(RangeIndex, (a, b) =$D(
binaryFun!less(*a, *b))) thus reflecting the ordering of the binaryFun!less(*a, *b))) thus reflecting the ordering of the
index. The index-based version returns $(D void) because the ordering index. The index-based version returns `void` because the ordering
relation involves not only $(D index) but also $(D r). relation involves not only `index` but also `r`.
Throws: If the second argument's length is less than that of the range Throws: If the second argument's length is less than that of the range
indexed, an exception is thrown. indexed, an exception is thrown.
@ -1440,18 +1440,15 @@ private template validPredicates(E, less...)
} }
/** /**
$(D auto multiSort(Range)(Range r)
if (validPredicates!(ElementType!Range, less));)
Sorts a range by multiple keys. The call $(D multiSort!("a.id < b.id", Sorts a range by multiple keys. The call $(D multiSort!("a.id < b.id",
"a.date > b.date")(r)) sorts the range $(D r) by $(D id) ascending, "a.date > b.date")(r)) sorts the range `r` by `id` ascending,
and sorts elements that have the same $(D id) by $(D date) and sorts elements that have the same `id` by `date`
descending. Such a call is equivalent to $(D sort!"a.id != b.id ? a.id descending. Such a call is equivalent to $(D sort!"a.id != b.id ? a.id
< b.id : a.date > b.date"(r)), but $(D multiSort) is faster because it < b.id : a.date > b.date"(r)), but `multiSort` is faster because it
does fewer comparisons (in addition to being more convenient). does fewer comparisons (in addition to being more convenient).
Returns: Returns:
The initial range wrapped as a $(D SortedRange) with its predicates The initial range wrapped as a `SortedRange` with its predicates
converted to an equivalent single predicate. converted to an equivalent single predicate.
*/ */
template multiSort(less...) //if (less.length > 1) template multiSort(less...) //if (less.length > 1)
@ -1799,14 +1796,14 @@ private void sort5(alias lt, Range)(Range r)
// sort // sort
/** /**
Sorts a random-access range according to the predicate $(D less). Performs Sorts a random-access range according to the predicate `less`. Performs
$(BIGOH r.length * log(r.length)) evaluations of $(D less). If `less` involves $(BIGOH r.length * log(r.length)) evaluations of `less`. If `less` involves
expensive computations on the _sort key, it may be worthwhile to use expensive computations on the _sort key, it may be worthwhile to use
$(LREF schwartzSort) instead. $(LREF schwartzSort) instead.
Stable sorting requires $(D hasAssignableElements!Range) to be true. Stable sorting requires `hasAssignableElements!Range` to be true.
$(D sort) returns a $(REF SortedRange, std,range) over the original range, `sort` returns a $(REF SortedRange, std,range) over the original range,
allowing functions that can take advantage of sorted data to know that the allowing functions that can take advantage of sorted data to know that the
range is sorted and adjust accordingly. The $(REF SortedRange, std,range) is a range is sorted and adjust accordingly. The $(REF SortedRange, std,range) is a
wrapper around the original range, so both it and the original range are sorted. wrapper around the original range, so both it and the original range are sorted.
@ -1815,14 +1812,14 @@ they $(I can) know that $(REF SortedRange, std,range) has been sorted.
Preconditions: Preconditions:
The predicate is expected to satisfy certain rules in order for $(D sort) to The predicate is expected to satisfy certain rules in order for `sort` to
behave as expected - otherwise, the program may fail on certain inputs (but not behave as expected - otherwise, the program may fail on certain inputs (but not
others) when not compiled in release mode, due to the cursory $(D assumeSorted) others) when not compiled in release mode, due to the cursory `assumeSorted`
check. Specifically, $(D sort) expects $(D less(a,b) && less(b,c)) to imply check. Specifically, `sort` expects `less(a,b) && less(b,c)` to imply
$(D less(a,c)) (transitivity), and, conversely, $(D !less(a,b) && !less(b,c)) to `less(a,c)` (transitivity), and, conversely, `!less(a,b) && !less(b,c)` to
imply $(D !less(a,c)). Note that the default predicate ($(D "a < b")) does not imply `!less(a,c)`. Note that the default predicate (`"a < b"`) does not
always satisfy these conditions for floating point types, because the expression always satisfy these conditions for floating point types, because the expression
will always be $(D false) when either $(D a) or $(D b) is NaN. will always be `false` when either `a` or `b` is NaN.
Use $(REF cmp, std,math) instead. Use $(REF cmp, std,math) instead.
Params: Params:
@ -1830,8 +1827,8 @@ Params:
ss = The swapping strategy to use. ss = The swapping strategy to use.
r = The range to sort. r = The range to sort.
Returns: The initial range wrapped as a $(D SortedRange) with the predicate Returns: The initial range wrapped as a `SortedRange` with the predicate
$(D binaryFun!less). `binaryFun!less`.
Algorithms: $(HTTP en.wikipedia.org/wiki/Introsort, Introsort) is used for unstable sorting and Algorithms: $(HTTP en.wikipedia.org/wiki/Introsort, Introsort) is used for unstable sorting and
$(HTTP en.wikipedia.org/wiki/Timsort, Timsort) is used for stable sorting. $(HTTP en.wikipedia.org/wiki/Timsort, Timsort) is used for stable sorting.
@ -2882,14 +2879,14 @@ sort!((a, b) => hashFun(a) < hashFun(b))(array);
schwartzSort!(hashFun, "a < b")(array); schwartzSort!(hashFun, "a < b")(array);
---- ----
The $(D schwartzSort) function might require less temporary data and The `schwartzSort` function might require less temporary data and
be faster than the Perl idiom or the decorate-sort-undecorate idiom be faster than the Perl idiom or the decorate-sort-undecorate idiom
present in Python and Lisp. This is because sorting is done in-place present in Python and Lisp. This is because sorting is done in-place
and only minimal extra data (one array of transformed elements) is and only minimal extra data (one array of transformed elements) is
created. created.
To check whether an array was sorted and benefit of the speedup of To check whether an array was sorted and benefit of the speedup of
Schwartz sorting, a function $(D schwartzIsSorted) is not provided Schwartz sorting, a function `schwartzIsSorted` is not provided
because the effect can be achieved by calling $(D because the effect can be achieved by calling $(D
isSorted!less(map!transform(r))). isSorted!less(map!transform(r))).
@ -2899,8 +2896,8 @@ Params:
ss = The swapping strategy to use. ss = The swapping strategy to use.
r = The range to sort. r = The range to sort.
Returns: The initial range wrapped as a $(D SortedRange) with the Returns: The initial range wrapped as a `SortedRange` with the
predicate $(D (a, b) => binaryFun!less(transform(a), predicate `(a, b) => binaryFun!less(transform(a)$D(
transform(b))). transform(b))).
*/ */
SortedRange!(R, ((a, b) => binaryFun!less(unaryFun!transform(a), SortedRange!(R, ((a, b) => binaryFun!less(unaryFun!transform(a),
@ -3018,11 +3015,11 @@ if (isRandomAccessRange!R && hasLength!R)
// partialSort // partialSort
/** /**
Reorders the random-access range $(D r) such that the range $(D r[0 Reorders the random-access range `r` such that the range `r[$D(
.. mid]) is the same as if the entire $(D r) were sorted, and leaves .. mid]) is the same as if the entire `r` were sorted, and leaves
the range $(D r[mid .. r.length]) in no particular order. Performs the range `r[mid .. r.length]` in no particular order. Performs
$(BIGOH r.length * log(mid)) evaluations of $(D pred). The $(BIGOH r.length * log(mid)) evaluations of `pred`. The
implementation simply calls $(D topN!(less, ss)(r, n)) and then $(D implementation simply calls `topN!(less, ss)(r, n)` and then $(D
sort!(less, ss)(r[0 .. n])). sort!(less, ss)(r[0 .. n])).
Params: Params:
@ -3077,17 +3074,17 @@ if (isRandomAccessRange!(Range1) && hasLength!Range1 &&
// topN // topN
/** /**
Reorders the range $(D r) using $(D swap) such that $(D r[nth]) refers Reorders the range `r` using `swap` such that `r[nth]` refers
to the element that would fall there if the range were fully to the element that would fall there if the range were fully
sorted. In addition, it also partitions $(D r) such that all elements sorted. In addition, it also partitions `r` such that all elements
$(D e1) from $(D r[0]) to $(D r[nth]) satisfy $(D !less(r[nth], e1)), `e1` from `r[0]` to `r[nth]` satisfy `!less(r[nth], e1)`,
and all elements $(D e2) from $(D r[nth]) to $(D r[r.length]) satisfy and all elements `e2` from `r[nth]` to `r[r.length]` satisfy
$(D !less(e2, r[nth])). Effectively, it finds the nth smallest `!less(e2, r[nth])`. Effectively, it finds the nth smallest
(according to $(D less)) elements in $(D r). Performs an expected (according to `less`) elements in `r`. Performs an expected
$(BIGOH r.length) (if unstable) or $(BIGOH r.length * log(r.length)) $(BIGOH r.length) (if unstable) or $(BIGOH r.length * log(r.length))
(if stable) evaluations of $(D less) and $(D swap). (if stable) evaluations of `less` and `swap`.
If $(D n >= r.length), the algorithm has no effect and returns If `n >= r.length`, the algorithm has no effect and returns
`r[0 .. r.length]`. `r[0 .. r.length]`.
Params: Params:
@ -3668,11 +3665,11 @@ if (isRandomAccessRange!(Range1) && hasLength!Range1 &&
} }
/** /**
Copies the top $(D n) elements of the Copies the top `n` elements of the
$(REF_ALTTEXT input range, isInputRange, std,range,primitives) $(D source) into the $(REF_ALTTEXT input range, isInputRange, std,range,primitives) `source` into the
random-access range $(D target), where $(D n = random-access range `target`, where `n $D(
target.length). Elements of $(D source) are not touched. If $(D target.length). Elements of `source` are not touched. If $(D
sorted) is $(D true), the target is sorted. Otherwise, the target sorted) is `true`, the target is sorted. Otherwise, the target
respects the $(HTTP en.wikipedia.org/wiki/Binary_heap, heap property). respects the $(HTTP en.wikipedia.org/wiki/Binary_heap, heap property).
Params: Params:
@ -3735,7 +3732,7 @@ Similar to $(LREF topN), except that the range is not modified.
Params: Params:
less = A binary predicate that defines the ordering of range elements. less = A binary predicate that defines the ordering of range elements.
Defaults to $(D a < b). Defaults to `a < b`.
ss = $(RED (Not implemented yet.)) Specify the swapping strategy. ss = $(RED (Not implemented yet.)) Specify the swapping strategy.
r = A r = A
$(REF_ALTTEXT random-access range, isRandomAccessRange, std,range,primitives) $(REF_ALTTEXT random-access range, isRandomAccessRange, std,range,primitives)
@ -3743,13 +3740,13 @@ Params:
index = A index = A
$(REF_ALTTEXT random-access range, isRandomAccessRange, std,range,primitives) $(REF_ALTTEXT random-access range, isRandomAccessRange, std,range,primitives)
with assignable elements to build the index in. The length of this range with assignable elements to build the index in. The length of this range
determines how many top elements to index in $(D r). determines how many top elements to index in `r`.
This index range can either have integral elements, in which case the This index range can either have integral elements, in which case the
constructed index will consist of zero-based numerical indices into constructed index will consist of zero-based numerical indices into
$(D r); or it can have pointers to the element type of $(D r), in which `r`; or it can have pointers to the element type of `r`, in which
case the constructed index will be pointers to the top elements in case the constructed index will be pointers to the top elements in
$(D r). `r`.
sorted = Determines whether to sort the index by the elements they refer sorted = Determines whether to sort the index by the elements they refer
to. to.
@ -3852,7 +3849,7 @@ Private for the time being.
Computes the median of 2 to 5 arbitrary indexes in random-access range `r` Computes the median of 2 to 5 arbitrary indexes in random-access range `r`
using hand-written specialized algorithms. The indexes must be distinct (if not, using hand-written specialized algorithms. The indexes must be distinct (if not,
behavior is implementation-defined). The function also partitions the elements behavior is implementation-defined). The function also partitions the elements
involved around the median, e.g. $(D medianOf(r, a, b, c)) not only fills `r[b]` involved around the median, e.g. `medianOf(r, a, b, c)` not only fills `r[b]`
with the median of `r[a]`, `r[b]`, and `r[c]`, but also puts the minimum in with the median of `r[a]`, `r[b]`, and `r[c]`, but also puts the minimum in
`r[a]` and the maximum in `r[c]`. `r[a]` and the maximum in `r[c]`.
@ -3861,9 +3858,9 @@ less = The comparison predicate used, modeled as a
$(LINK2 https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings, strict weak ordering) $(LINK2 https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings, strict weak ordering)
(irreflexive, antisymmetric, transitive, and implying a transitive equivalence). (irreflexive, antisymmetric, transitive, and implying a transitive equivalence).
flag = Used only for even values of `T.length`. If `No.leanRight`, the median flag = Used only for even values of `T.length`. If `No.leanRight`, the median
"leans left", meaning $(D medianOf(r, a, b, c, d)) puts the lower median of the "leans left", meaning `medianOf(r, a, b, c, d)` puts the lower median of the
four in `r[b]`, the minimum in `r[a]`, and the two others in `r[c]` and `r[d]`. four in `r[b]`, the minimum in `r[a]`, and the two others in `r[c]` and `r[d]`.
Conversely, $(D median!("a < b", Yes.leanRight)(r, a, b, c, d)) puts the upper Conversely, `median!("a < b", Yes.leanRight)(r, a, b, c, d)` puts the upper
median of the four in `r[c]`, the maximum in `r[d]`, and the two others in median of the four in `r[c]`, the maximum in `r[d]`, and the two others in
`r[a]` and `r[b]`. `r[a]` and `r[b]`.
r = The range containing the indexes. r = The range containing the indexes.
@ -4025,16 +4022,16 @@ if (isRandomAccessRange!Range && hasLength!Range &&
// nextPermutation // nextPermutation
/** /**
* Permutes $(D range) in-place to the next lexicographically greater * Permutes `range` in-place to the next lexicographically greater
* permutation. * permutation.
* *
* The predicate $(D less) defines the lexicographical ordering to be used on * The predicate `less` defines the lexicographical ordering to be used on
* the range. * the range.
* *
* If the range is currently the lexicographically greatest permutation, it is * If the range is currently the lexicographically greatest permutation, it is
* permuted back to the least permutation and false is returned. Otherwise, * permuted back to the least permutation and false is returned. Otherwise,
* true is returned. One can thus generate all permutations of a range by * true is returned. One can thus generate all permutations of a range by
* sorting it according to $(D less), which produces the lexicographically * sorting it according to `less`, which produces the lexicographically
* least permutation, and then calling nextPermutation until it returns false. * least permutation, and then calling nextPermutation until it returns false.
* This is guaranteed to generate all distinct permutations of the range * This is guaranteed to generate all distinct permutations of the range
* exactly once. If there are $(I N) elements in the range and all of them are * exactly once. If there are $(I N) elements in the range and all of them are
@ -4252,10 +4249,10 @@ if (isBidirectionalRange!BidirectionalRange &&
// nextEvenPermutation // nextEvenPermutation
/** /**
* Permutes $(D range) in-place to the next lexicographically greater $(I even) * Permutes `range` in-place to the next lexicographically greater $(I even)
* permutation. * permutation.
* *
* The predicate $(D less) defines the lexicographical ordering to be used on * The predicate `less` defines the lexicographical ordering to be used on
* the range. * the range.
* *
* An even permutation is one which is produced by swapping an even number of * An even permutation is one which is produced by swapping an even number of