Reducing a Sequence with Any or All

Existential and universal checks summarize a sequence of predicates and can finish before visiting every item.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Read the empty results
  2. Choose a revealing test
  3. Look for a witness or a counterexample
  4. Retain a useful record when the caller needs evidence

Read the empty results

Python's any returns false on empty input and all returns true. There is no witness for any and no counterexample for all. This matters when a missing list should have a separate result under the input contract.

Choose a revealing test

For 2, minus 1, and 4, checking whether all items are positive can stop after minus 1. An iterator with side effects may therefore leave 4 unread. Short-circuit behavior also explains why a single long Boolean expression can do less work than expected.[1]

Look for a witness or a counterexample

An “any” query asking if an export has an invalid row can stop as soon as such a row is found. An “all” query asking if its rows are valid can stop when it finds the same counterexample. Both can return different Boolean values after examining the same prefix. When there are no rows, any is false and all is true under standard empty-fold rules. Quantified conditions explains why no counterexample exists for the empty universal claim.

Retain a useful record when the caller needs evidence

A Boolean result alone does not identify the offending row. A first-match helper can return the row and its position. If the report must include all failed rows, a single short-circuit check cannot supply them. Plan the traversal from the output contract. See first-match scans.

For a test, supply valid, invalid, valid and observe that the third predicate need not run. This is especially useful when the source is consumed as it is read. Add a separate rule for input that must exist and be nonempty if an empty list should not count as a successful validation.

References

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