list res8: List[Option[Int]] = List(Some(1), Some(2), None) I can get ...">

"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) 
+5
source share
2 answers

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 
+13
source

You could just ask Hoogle . This is a search engine for Haskell functions: you enter a type and offer functions that you can use for that type. For type [Maybe a] -> [a] its first result is catMaybes from Data.Maybe .

+9
source

Source: https://habr.com/ru/post/1200706/


All Articles