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:
> 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With