The OpenD Programming Language

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).

  1. InputRange find(InputRange haystack)
  2. InputRange find(InputRange haystack, Element needle)
    InputRange
    find
    (
    alias pred = "a == b"
    InputRange
    Element
    )
    (
    InputRange haystack
    ,
    scope Element needle
    )
    if (
    isInputRange!InputRange &&
    is(typeof(binaryFun!pred(haystack.front, needle)) : bool)
    &&
    !is(typeof(binaryFun!pred(haystack.front, needle.front)) : bool)
    )
  3. R1 find(R1 haystack, R2 needle)
  4. Tuple!(Range, size_t) find(Range haystack, Needles needles)
  5. RandomAccessRange find(RandomAccessRange haystack, BoyerMooreFinder!(pred, InputRange) needle)

Parameters

pred

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

haystack InputRange

The input range searched in.

needle Element

The element searched for.

Return Value

Type: InputRange

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.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);
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)]);

See Also

Meta