Finding the First Matching Item

A first-match scan returns the earliest visited item satisfying a predicate and stops as soon as it has that witness.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Define first
  2. Show the missing case
  3. Preserve the identity of the first witness
  4. Make completion distinct from a valid match with an empty value

Define first

Scanning 9, 14, 12 for an even value returns 14. Choosing the smallest even would require looking at 12 as well. A function contract can define what traversal order makes a match first and what to return if none qualifies.

Show the missing case

An empty sequence finds nothing. So does 9, 13. If the result could itself be None, an explicit found flag or a distinct sentinel disambiguates the outcome. See sentinel values for preserving valid values.[1]

Preserve the identity of the first witness

Suppose an input is [open, blocked, open], and the predicate selects open entries. A front-to-back scan returns the position zero and can stop before reading the others. A reverse scan reaches position two first. If each entry shares a display value with another, returning its position or record ID keeps which one was selected visible. Front and back scans gives the order distinction.

Make completion distinct from a valid match with an empty value

If None is a legitimate matching item, returning it for both matching and missing is ambiguous. Returning a found indicator and value or a distinct sentinel supplies a more useful result. Test an empty input, all failed predicates, a first-position match, and a valid match whose payload is null.

For a lazy source, early completion may leave entries unread. The caller is responsible for the source lifetime according to its contract. Iterator exhaustion explains why a consumed prefix and a fully consumed iterator leave different state for a later step.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩