list res8: List[Option[Int]] = List(Some(1), Some(2), None) 我可以得到Lis-6ren">
gpt4 book ai didi

scala - "Flattening"Scala 和 Haskell 中的列表

转载 作者:行者123 更新时间:2023-12-04 16:22:04 33 4
gpt4 key购买 nike

给定一个 List[Option[Int]] :

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

我可以得到 List(1,2) ,即提取 list通过 flatMapflatten :
scala> list.flatten
res9: List[Int] = List(1, 2)

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

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

我尝试了以下失败:
import Control.Monad

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

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

最佳答案

您可以使用 catMaybes :

import Data.Maybe
catMaybes xs

如果你想使用 >>=你需要一个函数 Maybe a -> [a] .这是 maybeToList :
xs >>= maybeToList

正如评论指出的那样,您可以转换任何 Foldable到列表中,以便您可以制作 flatten'更一般的:
flatten' :: Foldable f => [f a] -> [a]
flatten' xs = xs >>= toList

关于scala - "Flattening"Scala 和 Haskell 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25393698/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com