find

Finds an individual element in an input range. Elements of haystack are compared with needle by using predicate pred with pred(haystack.front, needle). The predicate is passed to std.functional.binaryFun, and can either accept a string, or any callable that can be executed via pred(element, element).

If haystack is a forward range, needle can be a forward range too. In this case startsWith!pred(haystack, needle) is evaluated on each evaluation.

To find the first element not matching the needle, use predicate "a != b".

Complexity: find performs O(walkLength(haystack)) evaluations of pred. There are specializations that improve performance by taking advantage of bidirectional or random access ranges (where possible).

Parameters

pred

The predicate for comparing each element with the needle, defaulting to equality "a == b".

haystack R1

The input range searched in.

needle R2

The element searched for.

Return Value

Type: R1

haystack advanced such that the front element is the one searched for; that is, until binaryFun!pred(haystack.front, needle) is true. If no such position exists, returns an empty haystack.

Examples

import std.container : SList;
import std.range.primitives : empty;
import std.typecons : Tuple;

assert(find("hello, world", "World").empty);
assert(find("hello, world", "wo") == "world");
assert([1, 2, 3, 4].find(SList!int(2, 3)[]) == [2, 3, 4]);
alias C = Tuple!(int, "x", int, "y");
auto a = [C(1,0), C(2,0), C(3,1), C(4,0)];
assert(a.find!"a.x == b"([2, 3]) == [C(2,0), C(3,1), C(4,0)]);
assert(a[1 .. $].find!"a.x == b"([2, 3]) == [C(2,0), C(3,1), C(4,0)]);
import std.range.primitives;

auto arr = [1, 2, 4, 4, 4, 4, 5, 6, 9];
assert(arr.find(4) == [4, 4, 4, 4, 5, 6, 9]);
assert(arr.find(1) == arr);
assert(arr.find(9) == [9]);
assert(arr.find!((e, n) => e > n)(4) == [5, 6, 9]);
assert(arr.find!((e, n) => e < n)(4) == arr);
assert(arr.find(0).empty);
assert(arr.find(10).empty);
assert(arr.find(8).empty);

assert(find("hello, world", ',') == ", world");

Case-insensitive find of a string

import std.range.primitives;
import std.uni : toLower;

string[] s = ["Hello", "world", "!"];
assert(s.find!((e, n) => toLower(e) == n)("hello") == s);

See Also

Meta