flatmap列表和Maybes

时间:2012-02-28 09:54:07

标签: haskell

我正在搜索可以同时映射和展平列表和Maybes的代码。我在this topic中找到了这样一个flatMap函数:

flatMap :: (t -> [a]) -> [t] -> [a]
flatMap _ [] = []
flatMap f (x:xs) = f x ++ flatMap f xs

这很好用:

> flatMap id [[],[1,2],[3],[],[4,5,6]]
[1,2,3,4,5,6]

唯一的问题是它不适用于Maybes。相反,我必须使用Data.Maybe.mapMaybe

> Data.Maybe.mapMaybe id [Just 1, Nothing, Just 2, Just 3, Nothing]
[1,2,3]

是否有一个内置函数可以同时处理Lists和Maybes(以及其他一些类型)?

1 个答案:

答案 0 :(得分:11)

我认为Data.Foldable可能正是您所寻找的:

> let flatMap f = concatMap (Data.Foldable.toList . f)
> :t flatMap
flatMap :: Data.Foldable.Foldable t => (a -> t b) -> [a] -> [b]
> flatMap id [[],[1,2],[3],[],[4,5,6]]
[1,2,3,4,5,6]
> flatMap id [Just 1, Nothing, Just 2, Just 3, Nothing]
[1,2,3]