5

我想有一个类型的函数:

f :: [Maybe a] -> Maybe [a]

例如

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

catMaybes :: [Maybe a] -> [a]和in差不多Data.Maybe,只是catMaybes忽略了Nothing,而myf是很认真的Nothing。我可以f以一种天真的方式实现(如下所示),但想知道是否有更惯用的方式(如“应用函子”):

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
4

2 回答 2

21

您正在搜索的功能称为序列:

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的序列就足够了。

于 2013-08-02T00:29:31.107 回答
7

你想sequenceControl.Monad.

(这在 中也以有用的方式概括Data.Traversable。)

于 2013-08-02T00:28:45.097 回答