[Haskell-cafe] Lenses and Nested Maps

Jack Kelly jack at jackkelly.name
Tue Jun 18 03:56:40 UTC 2019


Henry Laxen <nadine.and.henry at pobox.com> writes:

> s :: Map String (Map Int Char)
> s =  M.fromList [("alice", M.fromList [(5,'a')]), ("bob", M.fromList [(6,'b')])]

`ix` will give you a `Traversal` that targets a given key. If it's not
present in the map, you get a `Traversal` that hits no targets.

t :: Map String (Map Int Char)
t = s & ix "bob" . ix 6 %~ succ

*Main> t
fromList [("alice",fromList [(5,'a')]),("bob",fromList [(6,'c')])]

If you want more control (to set or delete values, for instance), the
`at` function gives you a lens that views a `Maybe`. Writing `Just` into
the lens creates the value at the key, and writing `Nothing` into the
lens removes the value at the key. The `(?~)` operator, and the `_Just`
prism may be useful to you if you use `at`.

HTH,

-- Jack


More information about the Haskell-Cafe mailing list