说我有一个列表:
[Nothing, Just 1, Nothing, Just 2]
我想获得第一个Just
(非错误)值;在这种情况下,它是Just 1
。我唯一能想到的是:
firstJust xs = case filter isJust xs of
[] -> Nothing
Just x -> Just x
有没有更好的/ monad-generic方法来做到这一点?
答案 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