'selective' map 的 Haskell 习语

标签 haskell dictionary

假设有人想要映射一个集合,但仅在映射值满足特定条件时才收集映射函数的结果。我目前正在这样做:

func = foldl (\acc x, ->  (maybeGrab x):acc) []


maybeGrab a
    | a > 5 = [someFunc a]
    | otherwise = []

虽然这有效,但我确信有一种更惯用的“正确/常见/更容易识别”的方式来做到这一点。

最佳答案

 mapMaybe :: (a -> Maybe b) -> [a] -> [b]
Data.Maybe 包中的

mapMaybe 看起来可以完成这项工作。文档说:

The mapMaybe function is a version of map which can throw out elements. In particular, the functional argument returns something of type Maybe b. If this is Nothing, no element is added on to the result list. If it just Just b, then b is included in the result list.

关于 'selective' map 的 Haskell 习语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7868578/

相关文章:

python - Python 中的 OrderedDict 与字典

python - 从字典中删除一个元素

haskell - 无法匹配预期类型 IO t

haskell - Fay 找不到 fay-base

c# - 字典错误调试中不存在给定的键

python - 排序的字典返回没有意义/python

dictionary - 如何解决 fatal error : concurrent map read and map write

haskell - Yesod 中的复合主键

haskell - c2hs 输入输出类型编码

haskell - 如何让 ReaderT 与另一个 monad 转换器一起工作?