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

kir*_*sos 7 monads haskell maybe

说我有一个列表,如:

[Nothing, Just 1, Nothing, Just 2]
Run Code Online (Sandbox Code Playgroud)

我想得到第一个Just(非错误)值; 在这种情况下,它是Just 1.我唯一能想到的是:

firstJust xs = case filter isJust xs of
                 []     -> Nothing
                 Just x -> Just x
Run Code Online (Sandbox Code Playgroud)

有没有更好的/ monad-generic方法来做到这一点?

beh*_*uri 17

msum来自Control.Monad:

\> msum [Nothing, Just 1, Nothing, Just 2]
Just 1
Run Code Online (Sandbox Code Playgroud)

asum来自Data.Foldable:

\> asum [Nothing, Just 1, Nothing, Just 2]
Just 1
Run Code Online (Sandbox Code Playgroud)

两者都记录为:

一系列动作的总和,概括concat.

签名:

msum :: (Foldable t, MonadPlus m) => t (m a) -> m a
asum :: (Foldable t, Alternative f) => t (f a) -> f a
Run Code Online (Sandbox Code Playgroud)

并且由于Maybe实例Alternative而表现如上.

  • 通过从'Maybe`切换到`First`,你可以使用`fold`. (3认同)