简体   繁体   中英

“Flattening” a List in Scala & Haskell

Given a List[Option[Int]] :

scala> list
res8: List[Option[Int]] = List(Some(1), Some(2), None)

I can get List(1,2) , ie extract the 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 perform 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 a function Maybe a -> [a] . This is maybeToList :

xs >>= maybeToList

As the comment point out, you can convert any Foldable to a list so you can make flatten' more general:

flatten' :: Foldable f => [f a] -> [a]
flatten' xs = xs >>= toList

You could have just asked Hoogle . It's a search engine for Haskell functions: you enter a type and it proposes functions that can be used at such type. For the type [Maybe a] -> [a] , its first result is catMaybes from Data.Maybe .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM