Search code examples
haskellhaskell-lensoption-typelenses

How to use lens set function with Maybe?


I have a tuple x and a Maybe value y

x = (1,1)
y = Just 2

I can do this

z = maybe x (\v -> x & _1 .~ v) y

Or I can create my own operator

(.~?) x y =  x %~ (\v -> fromMaybe v y)

z = x & _1 .~? y

But if lens doesn't have such operator, maybe I don't need it?

So, how to use lens set function with Maybe?


Solution

  • It appears that you want

    maybeSetFst :: (a, b) -> Maybe a -> (a, b)
    

    which will update the first field if given an update value and will leave it alone otherwise. I think the first implementation you give is very good, but you can give it a more general type:

    maybeSetFst :: Field1 s s a a => s -> Maybe a -> s
    

    If you don't want that generality, you can skip the lenses and write (using TupleSections)

    maybeSetFst p@(_,b) = maybe p (,b)
    

    Another option is to apply maybe to get the update function:

    maybeSetFst p m = maybe id (_1 .~) m p
    

    which can be written

    maybeSetFst = flip $ maybe id (_1 .~)
    

    for point-free silliness.