haskell中的函数类似于catMaybes,但有类型[Maybe a] - >也许[a]

时间:2013-08-02 00:25:28

标签: haskell functor applicative

我想要一个类型为

的函数
f :: [Maybe a] -> Maybe [a]

e.g。

f [Just 3, Just 5] == Just [3, 5]
f [Just 3, Nothing] == Nothing
f [] == Just []

catMaybes :: [Maybe a] -> [a]中的Data.Maybe相似,但catMaybes忽略Nothing,而fNothing非常认真。我可以以天真的方式实现f(如下所示),但想知道是否有更多的惯用方式(如“applicative functor”):

f :: [Maybe a] -> Maybe [a]
f xs = let ys = catMaybes xs
        in if length ys == length xs 
           then Just ys
           else Nothing

f :: [Maybe a] -> Maybe [a]
f xs = if all isJust xs
        then catMaybes xs
        else Nothing

2 个答案:

答案 0 :(得分:20)

您要搜索的功能称为序列:

sequence :: (Monad m) => [m a] -> m [a]

您可以使用hoogle找到此功能:link

示例:

>>> sequence [Just 3, Just 5]
Just [3,5]

>>> sequence [] :: Maybe [Int]
Just []

注意:Data.Traversable中的sequenceA也有点概括,但对于您的用例,来自Control.Monad的序列就足够了。

答案 1 :(得分:7)

您希望来自Control.Monad的{​​{3}}。

(这也在sequence中以有用的方式推广。)