我想要一个类型为
的函数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
,而f
对Nothing
非常认真。我可以以天真的方式实现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
答案 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
中以有用的方式推广。)