[Haskell-beginners] a simple little problem
Brent Yorgey
byorgey at seas.upenn.edu
Sun Aug 14 18:36:43 CEST 2011
On Sat, Aug 13, 2011 at 02:47:04PM -0400, Brandon Allbery wrote:
> On Sat, Aug 13, 2011 at 14:04, Dennis Raddle <dennis.raddle at gmail.com>wrote:
>
> > Can someone suggest an elegant way to write the following?
> >
> > fn :: [Maybe Float] -> Maybe Float
> >
> > in which, if the input list has all Nothing, then the result is Nothing
> > if the input list has one or more Just x, then the result is Just x
> > (in which the x is picked arbitrarily, could be the first one or last
> > one)
> >
>
> Isn't this just mconcat?
No. The Monoid instance for Maybe defined in Data.Monoid is the one
which lifts a Monoid instance on a to a Monoid instance on Maybe a.
That is, all the Nothings are discarded and all the Justs combined
according to the Monoid instance on a. For example:
> mconcat [Nothing, Just "hello", Nothing, Just "world"]
Just "helloworld"
The MonadPlus instance for Maybe is what the OP wants (as I think
someone else already pointed out), which is sensible, since the Maybe
monad models possible failure, and hence the MonadPlus instance models
choosing the first success.
-Brent
More information about the Beginners
mailing list