Search code examples
haskellhaskell-lens

Analog of `<<%~` not requiring Monoid for Traversal


I need a function like <<%~ which would act with Traversals in similar fashion to ^?, like this:

(<<?%~) :: Traversal s t a b -> (a -> b) -> s -> (Maybe a, t)

> ix 0 <<?%~ succ $ [1,2]
(Just 1,[2,2])
> ix 1 <<?%~ succ $ [1,2]
(Just 2,[1,3])
> ix 2 <<?%~ succ $ [1,2]
(Nothing,[1,2])

How should I implement it? The obvious way is to apply ^? and %~ separately, but I'd like a solution in one go.


Solution

  • If we don't want to require a Monoid constraint on the targets, we have to specify ourselves the Monoid that will be used for combining the old elements in a traversal. As the goal is something analogous to ^?, the appropriate monoid is First.

    (<<?%~) :: LensLike ((,) (First a)) s t a b -> (a -> b) -> s -> (Maybe a, t)
    l <<?%~ f = first getFirst . (l $ \a -> (First (Just a), f a))