假设我有一个类似的列表:
[Nothing, Just 1, Nothing, Just 2]
我想得到第一个
Just
(非错误)值;在这种情况下,它是 Just 1
.我唯一能想到的是:firstJust xs = case filter isJust xs of
[] -> Nothing
Just x -> Just x
有没有更好的/单子(monad)通用的方法来做到这一点?
最佳答案
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
而表现如上.
关于haskell - 从 [Maybe a] 中提取第一个 Just 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36410971/