"Smoothing" a list in Scala & Haskell
Given List[Option[Int]] :
scala> list res8: List[Option[Int]] = List(Some(1), Some(2), None) I can get List(1,2) , i.e. extract list via flatMap and flatten :
scala> list.flatten res9: List[Int] = List(1, 2) scala> list.flatMap(x => x) res10: List[Int] = List(1, 2) Given the following [Maybe Int] in Haskell, how can I do the above operation?
I tried the following unsuccessfully:
import Control.Monad maybeToList :: Maybe a -> [b] maybeToList Just x = [x] maybeToList Nothing = [] flatten' :: [Maybe a] -> [a] flatten' xs = xs >>= (\y -> y >>= maybeToList) You can use catMaybes :
import Data.Maybe catMaybes xs if you want to use >>= , you need the Maybe a -> [a] function. This is maybeToList :
xs >>= maybeToList As the commentary suggests, you can convert any Foldable to a list to make flatten' more general:
flatten' :: Foldable f => [fa] -> [a] flatten' xs = xs >>= toList