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

标签 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)通用的方法来做到这一点?

最佳答案

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/

相关文章:

unit-testing - 我如何对 Alex 代码进行单元测试?

haskell - SDL_image 无法安装

javascript - 函数式编程将 Monad 数组转换为数组的单个 Monad

elm - 如何从 Elm Array 中过滤掉 "Nothing"值?

list - Haskell处理Maybe列表

haskell - 为什么 Maybe 的 Semigroup 实例偏向 Just 而 Monoid 使用 Nothing 作为其空元素?

haskell - 为什么这个类型注释是错误的?

mongodb - Haskell 扩展默认规则。更改默认值?

scala Iterable#map 与 Iterable#flatMap

functional-programming - 为什么 Maybe/Option 在 Clojure 中的使用不那么普遍?