How to compose lenses that return Maybe (Haskell)
Asked Answered
H

2

6

Suppose I have a lens like at _ that needs some Maybe a:

import Data.Map as M
m = M.fromList [(1,(2,3))]
--set 2nd element
m ^. at 1 .~ Just (4,5) 
--gives fromList [(1,(4,5))]
m ^. at 1 .~ Nothing
--gives fromList ()

Now suppose I want to compose it with another lens. The fact that this lens returns some Maybe a prevents me from doing it directly.

m ^. at 1 . _2 .~ Just 4
--error
-- I want to get M.fromList [(1,(2,4))]

What's the right way to do this?

Healing answered 13/1, 2016 at 5:4 Comment(0)
E
12

Use the _Just prism to set values in a Map conditional on whether the key exists. That's what prisms are for!

λ> let m = fromList [(1, (2, 3))]
λ> m & at 1 . _Just . _2 .~ 4
fromList [(1,(2,4))]
λ> m & at 100 . _Just . _2 .~ 4
fromList [(1,(2,3))]
Excite answered 13/1, 2016 at 5:16 Comment(0)
C
3

To set a value you can just write:

> m & ix 1 . _2 .~ 4
fromList [(1,(2,4))]

To get a value, you can do something similar:

> m ^? ix 1 . _2
Just 3
Carrelli answered 23/1, 2016 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.