"压扁" Scala中的列表&哈斯克尔

时间:2014-08-19 22:01:17

标签: scala haskell

给出List[Option[Int]]

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

我可以获得List(1,2),即通过listflatMap提取flatten

scala> list.flatten
res9: List[Int] = List(1, 2)

scala> list.flatMap(x => x)
res10: List[Int] = List(1, 2)

在Haskell中给出以下[Maybe Int],我该如何执行上述操作?

我尝试了以下尝试失败:

import Control.Monad

maybeToList :: Maybe a -> [b]
maybeToList Just x  = [x]
maybeToList Nothing = []

flatten' :: [Maybe a] -> [a]
flatten' xs = xs >>= (\y -> y >>= maybeToList)

2 个答案:

答案 0 :(得分:14)

您可以使用catMaybes

import Data.Maybe
catMaybes xs

如果您想使用>>=,则需要一个函数Maybe a -> [a]。这是maybeToList

xs >>= maybeToList

正如评论所指出的那样,您可以将任何Foldable转换为列表,这样您就可以使flatten'更加通用:

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

答案 1 :(得分:9)

您可能刚刚问过Hoogle。它是Haskell函数的搜索引擎:您输入一个类型,它提出了可以在这种类型中使用的函数。对于[Maybe a] -> [a]类型,其第一个结果是来自catMaybes的{​​{1}}。