Search code examples
haskellhaskell-lens

Is there a lens operator to combine %~ and fmap


I have the following code

u & currentDay %~ fmap (addDays 1)

currentDay returns a Maybe which is why I need the fmap. Is there already an operator to combine %~ and fmap (like %~<$> ;-)) or a clever way to do so ?


Solution

  • There is no existing operator for this but you could easily define your own:

    %$~ :: Functor f => ASetter s t (f a) (f b) -> (a -> b) -> s -> t
    l %$~ f = over a (fmap f)
    

    The standard way to do this is to use the mapped setter:

    u & currentDay . mapped %~ addDays 1
    

    Since your mapping over a Maybe you could also use _Just prism:

    u & currentDay . _Just %~ addDays 1