haskellmonadsoption-type

Extracting the first Just value from [Maybe a]


Say I have a list like:

[Nothing, Just 1, Nothing, Just 2]

I want to get the first Just (non-error) value; in this case, it's Just 1. The only thing I can think of is:

firstJust xs = case filter isJust xs of
                 []     -> Nothing
                 Just x -> Just x

Is there a better/monad-generic way to do this?


Solution

  • msum from Control.Monad:

    \> msum [Nothing, Just 1, Nothing, Just 2]
    Just 1
    

    or asum from Data.Foldable:

    \> asum [Nothing, Just 1, Nothing, Just 2]
    Just 1
    

    Both are documented as:

    The sum of a collection of actions, generalizing concat.

    with signature:

    msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
    asum :: (Foldable t, Alternative f) => t (f a) -> f a
    

    and behave as above due to Maybe instance of Alternative.