Lenses and Nested Maps

Hi Cafe, Suppose I have: s :: Map String (Map Int Char) s = M.fromList [("alice", M.fromList [(5,'a')]), ("bob", M.fromList [(6,'b')])] Is there any way to modify the 'b' entry easily using lenses? Thanks in advance. Best wishes, Henry Laxen

Hi Henry,
Yes, the "ix" function traverses into particular keys of map-like
structures https://www.stackage.org/haddock/lts-13.25/lens-4.17.1/Control-Lens-At.html#...
So, (s & ix "bob" . ix 6 .~ 'c') will yield a modified Map with 'b'
changed to 'c'.
-Michael
On Mon, Jun 17, 2019 at 9:45 PM Henry Laxen
Hi Cafe,
Suppose I have:
s :: Map String (Map Int Char) s = M.fromList [("alice", M.fromList [(5,'a')]), ("bob", M.fromList [(6,'b')])]
Is there any way to modify the 'b' entry easily using lenses?
Thanks in advance. Best wishes, Henry Laxen
_______________________________________________ Haskell-Cafe mailing list To (un)subscribe, modify options or view archives go to: http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe Only members subscribed via the mailman list are allowed to post.

The main lensy tools for maps are the At and Ixed classes, both found in
Control.Lens.At.
On Mon, Jun 17, 2019, 11:45 PM Henry Laxen
Hi Cafe,
Suppose I have:
s :: Map String (Map Int Char) s = M.fromList [("alice", M.fromList [(5,'a')]), ("bob", M.fromList [(6,'b')])]
Is there any way to modify the 'b' entry easily using lenses?
Thanks in advance. Best wishes, Henry Laxen
_______________________________________________ Haskell-Cafe mailing list To (un)subscribe, modify options or view archives go to: http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe Only members subscribed via the mailman list are allowed to post.

Henry Laxen
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
participants (4)
-
David Feuer
-
Henry Laxen
-
Jack Kelly
-
Michael Sloan