从 [Maybe a] 中提取第一个 Just 值

Extracting the first Just value from [Maybe a]

假设我有一个这样的列表:

[Nothing, Just 1, Nothing, Just 2]

我想获取第一个Just(非错误)值;在本例中,它是 Just 1。我唯一能想到的是:

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

是否有 better/monad-generic 方法来做到这一点?

msum 来自 Control.Monad:

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

asum 来自 Data.Foldable:

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

两者都记录为:

The sum of a collection of actions, generalizing concat.

有签名:

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

并且由于 Maybe instance of Alternative.

表现如上
import Data.Foldable (find)
import Data.Maybe (isJust)
import Control.Monad (join)

firstJust = join . find isJust

用法:

> firstJust [Nothing, Just 1, Nothing, Just 2]
Just 1

> firstJust [Nothing, Nothing]
Nothing