I’m searching for code which can map and flatten Lists and Maybes at the same time. I found such a flatMap-function in this topic:
flatMap :: (t -> [a]) -> [t] -> [a]
flatMap _ [] = []
flatMap f (x:xs) = f x ++ flatMap f xs
This works fine:
> flatMap id [[],[1,2],[3],[],[4,5,6]]
[1,2,3,4,5,6]
The only problem is that it doesn’t works for Maybes. Instead I have to use Data.Maybe.mapMaybe:
> Data.Maybe.mapMaybe id [Just 1, Nothing, Just 2, Just 3, Nothing]
[1,2,3]
Is there a single built-in function which can handle both Lists and Maybes (and maybe some other types)?
I think Data.Foldable may be what you’re looking for: