Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compose "Maybe" lenses?

If I have lenses for a nested record, where each lens returns a Maybe, how can I get them to compose, so that if anything in the "traversal" returns a Nothing the final result is a Nothing?

data Client = Client
  {
    clientProperties :: Maybe Properties
  , ...
  }

data Properties = Properties
  {
    propSmtpConfig :: Maybe SmtpConfig
  , ...
  }

c :: Client 
c = undefined

smtp = c ^. (properties . smtpConfig) -- How to make these lenses compose?

Edit I tried a lot of options, but this is the best I could come up with. Looking for something cleaner:

(client ^. properties) >>= (view smtpConfig)
like image 704
Saurabh Nanda Avatar asked Dec 03 '22 12:12

Saurabh Nanda


1 Answers

You can use the _Just prism. Here's a contrived example:

> (Just (Just 1, ()), ()) & _1 . _Just . _1 . _Just +~ 1
(Just (Just 2,()),())

In your case, I think you want

properties . _Just . smtpConfig . _Just
like image 155
Rein Henrichs Avatar answered Dec 19 '22 12:12

Rein Henrichs