LE

Lens

Lens optics library patterns for composable, type-safe data access and transformation in Haskell

Details

Language / Topic
haskellHaskell
Category
Libraries

Rules

balanced
- Generate record lenses with `makeLenses ''MyRecord` from `Control.Lens.TH` — prefix fields with `_` for the TH macro to discover them.
- Read with `view l s` or the infix `s ^. l` — navigate nested structures with `.`: `user ^. address . city`.
- Write with `set l v s` or `s & l .~ v` — chain modifications with `&`: `user & name .~ "Alice" & age .~ 30`.
- Modify with `over l f s` or `s & l %~ f` — compose lenses for deeply nested updates: `users & each . scores . each %~ (+1)`.
- Use `Prism`s for sum types: `_Just`, `_Left`, `_Right`, `_Cons` — `preview _Just mValue` safely unwraps `Maybe`.
- Use `Traversal` to update multiple targets: `users & each . age %~ (+1)` increments all ages in a list simultaneously.
- Use `at k .~ Just v` for `Map` inserts and `at k .~ Nothing` for deletes — cleaner than `Map.insert`/`Map.delete`.
- Use `zoom` in `State` monad to scope operations: `zoom (field1 . field2) $ modify (+1)` — keeps state operations focused on a subfield.