diff --git a/std/algorithm/searching.d b/std/algorithm/searching.d index 72a6f341d39..25379b58504 100644 --- a/std/algorithm/searching.d +++ b/std/algorithm/searching.d @@ -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)) { @@ -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 ]; diff --git a/std/range/primitives.d b/std/range/primitives.d index 7dc0d018a02..c1a139c136a 100644 --- a/std/range/primitives.d +++ b/std/range/primitives.d @@ -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; }