gpt4 book ai didi

'selective' map 的 Haskell 习语

转载 作者:行者123 更新时间:2023-12-02 19:05:40 25 4
gpt4 key购买 nike

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

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/

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