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

时间:2016-04-04 19:13:07

标签: haskell monads maybe

说我有一个列表:

[Nothing, Just 1, Nothing, Just 2]

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

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

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

2 个答案:

答案 0 :(得分:15)

来自Control.Monad

msum

\> msum [Nothing, Just 1, Nothing, Just 2]
Just 1
来自Data.Foldable

asum

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

两者均记录为:

  

行动集合的总和,概括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

并按上述行为。

答案 1 :(得分:2)

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