我想有一个类型的函数:
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