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
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
- Filtered Optics: A predicate that travels with the path
- Indexed Optics: Position-aware operations on collections
- Indexed Optics: Advanced Patterns: Paired indices and audit trails
- Each Type Class: One canonical traversal per container
- String Traversals: Characters, words and lines
- Indexed Access:
AtandIxedfor keys and indices
The Traversals & Practice Journey (28 exercises) covers filtering and indexed patterns alongside the basics.
Previous: List Decomposition Next: Filtered Optics