gpt4 book ai didi

haskell - flatmap 列表和可能

转载 作者:行者123 更新时间:2023-12-03 13:00:39 25 4
gpt4 key购买 nike

我正在寻找可以同时映射和展平 Lists 和 Maybes 的代码。我在 this topic 中发现了这样一个 flatMap 函数:

flatMap :: (t -> [a]) -> [t] -> [a]
flatMap _ [] = []
flatMap f (x:xs) = f x ++ flatMap f xs

这工作正常:
> flatMap id [[],[1,2],[3],[],[4,5,6]]
[1,2,3,4,5,6]

唯一的问题是它不适用于Maybes。相反,我必须使用 Data.Maybe.mapMaybe :
> Data.Maybe.mapMaybe id [Just 1, Nothing, Just 2, Just 3, Nothing]
[1,2,3]

是否有一个内置函数可以同时处理 Lists 和 Maybes(也许还有一些其他类型)?

最佳答案

我认为 Data.Foldable 可能是你要找的:

> let flatMap f = concatMap (Data.Foldable.toList . f)
> :t flatMap
flatMap :: Data.Foldable.Foldable t => (a -> t b) -> [a] -> [b]
> flatMap id [[],[1,2],[3],[],[4,5,6]]
[1,2,3,4,5,6]
> flatMap id [Just 1, Nothing, Just 2, Just 3, Nothing]
[1,2,3]

关于haskell - flatmap 列表和可能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9479757/

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