Precision and Filtering

"I believe the angle and direction of the lines are full of secret meaning."

– J.G. Ballard, Crash


Sometimes you don't want all the elements. You want the expensive ones, or the ones at certain indices, or the value at one key of a map. Filtering and indexing narrow a traversal's focus to exactly that subset. Here is the destination, before any theory: a bulk update to the chapter's Order, narrowed to only the lines that cost more than £10. The build compiles and runs it, and a test holds each value the comments show:

    var pricey =
        OrderTraversals.lines()
            .andThen(LineItemLenses.price())
            .filtered(price -> price.compareTo(new BigDecimal("10.00")) > 0);

    Order discounted =
        Traversals.modify(pricey, price -> price.subtract(new BigDecimal("5.00")), order);
    // Traversals.getAll(pricey, order)      -> [40.00]
    // Traversals.getAll(pricey, discounted) -> [35.00]
    // the £2.50 bulbs are untouched, and so is order itself

Why this matters

The predicate travels with the path, not with the loop body. Write if checks inside iteration and every caller must remember them; build the filter into the optic and the rule is declared once, composes with any lens or traversal, and cannot be forgotten at a call site. The same holds for position: an indexed traversal carries the index in the type instead of in a manually-threaded counter.

Most readers only need filtered traversals, covered first. The rest solve specific problems: reach for indexed optics when position drives the logic, At and Ixed for per-key access to a map or a list, Each for one canonical traversal per container, and string traversals for text. Read those pages when you hit them, not before. Decision Trees routes a constraint to its page.


Pages in this group

  1. Filtered Optics: A predicate that travels with the path
  2. Indexed Optics: Position-aware operations on collections
  3. Each Type Class: One canonical traversal per container
  4. String Traversals: Characters, words and lines
  5. Indexed Access: At and Ixed for keys and indices

Hands-On Learning

The Traversals & Practice Journey (28 exercises) covers filtering and indexed patterns alongside the basics.


Previous: List Decomposition Next: Filtered Optics