Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flatmap Lists and Maybes

Tags:

haskell

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)?

like image 887
kiritsuku Avatar asked Dec 22 '22 01:12

kiritsuku


1 Answers

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]
like image 151
hammar Avatar answered Jan 23 '23 17:01

hammar