How to create lenses that return Maybe (Haskell)

Suppose I have a type lens 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 combine it with another lens. The fact that this lens returns a part Maybe adoes not allow me to do this directly.

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

What is the right way to do this?

+4
source share
2 answers

Use a prism _Justto set the values ​​in Map associated with the key. Why do we need a prism!

λ> 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))]
+10
source

To set a value you can simply write:

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

To get the value, you can do something like this:

> m ^? ix 1 . _2
Just 3
+2

Source: https://habr.com/ru/post/1624040/


All Articles