Discussion: fold the Alts

David Feuer david.feuer at gmail.com
Sat Nov 8 19:06:49 UTC 2014


We've had First and Last in Data.Monoid for some time, and we now have Alt
as well. Unfortunately, we don't have nice convenient functions for using
them, the way we have sum and product to use Sum and Product. So we're
stuck with funny-looking constructions like listToMaybe . mapMaybe f for
lists, and nothing good for other containers.

My thought (the names firstAlt and lastAlt would absolutely have to be
changed to accommodate non-catch Alternatives, but I'm not inspired at
present):

firstAlt, lastAlt :: (Foldable f, Alternative m) => (a -> m b) -> f a -> m b

firstAlt f = getAlt #. foldMap (Alt #. f)

lastAlt f = getAlt #. getDual #. foldMap (Dual #. Alt #. f)

where
(#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c)
f #. g = coerce g

This specializes to Maybe very nicely:

firstMaybe :: Foldable f => (a -> Maybe b) -> f a -> Maybe b
firstMaybe = firstAlt

lastMaybe :: Foldable f => (a -> Maybe b) -> f a -> Maybe b
lastMaybe = lastAlt
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/libraries/attachments/20141108/b78f0691/attachment.html>


More information about the Libraries mailing list