Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion std/algorithm/searching.d
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ if (isForwardRange!R1 && !isInfinite!R1 &&
}

/// Ditto
size_t count(alias pred = "true", R)(R haystack)
size_t count(alias pred, R)(R haystack)
if (isInputRange!R && !isInfinite!R &&
is(typeof(unaryFun!pred(haystack.front)) : bool))
{
Expand All @@ -703,6 +703,16 @@ if (isInputRange!R && !isInfinite!R &&
return result;
}

/// Ditto
size_t count(R)(R haystack)
if (isInputRange!R && !isInfinite!R)
{
static if (hasLength!R)
return haystack.length;
else
return count!"true"(haystack);
}

@safe unittest
{
int[] a = [ 1, 2, 4, 3, 2, 5, 3, 2, 4 ];
Expand Down
31 changes: 15 additions & 16 deletions std/range/primitives.d
Original file line number Diff line number Diff line change
Expand Up @@ -1625,44 +1625,43 @@ range.
If $(D hasLength!Range), simply returns $(D range.length) without
checking $(D upTo) (when specified).

Otherwise, walks the range through its length and returns the number
of elements seen. Performes $(BIGOH n) evaluations of $(D range.empty)
Otherwise, walks the range for $(D upTo) elements. If $(D range.length) is smaller
than $(D upTo), the walking stops returning $(D range.length).

Performes $(BIGOH n) evaluations of $(D range.empty)
and $(D range.popFront()), where $(D n) is the effective length of $(D
range).

The $(D upTo) parameter is useful to "cut the losses" in case
the interest is in seeing whether the range has at least some number
of elements. If the parameter $(D upTo) is specified, stops if $(D
upTo) steps have been taken and returns $(D upTo).

Infinite ranges are compatible, provided the parameter $(D upTo) is
specified, in which case the implementation simply returns upTo.
*/
auto walkLength(Range)(Range range)
if (isInputRange!Range && !isInfinite!Range)
auto walkLength(Range)(Range range, const size_t upTo)
if (isInputRange!Range)
{
static if (hasLength!Range)
return range.length;
else static if (isInfinite!Range)
return upTo;
else
{
size_t result;
for ( ; !range.empty ; range.popFront() )
for ( ; result < upTo && !range.empty ; range.popFront() )
++result;
return result;
}
}
/// ditto
auto walkLength(Range)(Range range, const size_t upTo)
if (isInputRange!Range)

//@@@DEPRECATED_2018-07@@@
deprecated("use std.algorithm.searching.count instead.")
auto walkLength(Range)(Range range)
if (isInputRange!Range && !isInfinite!Range)
{
static if (hasLength!Range)
return range.length;
else static if (isInfinite!Range)
return upTo;
else
{
size_t result;
for ( ; result < upTo && !range.empty ; range.popFront() )
for ( ; !range.empty ; range.popFront() )
++result;
return result;
}
Expand Down