haskell - 使用 Maybe 返回函数映射和过滤 Maybe 列表

标签 haskell functional-programming option-type

我有一个可能的列表和一个给我节点颜色的函数(如果存在):

maybeNeighbors :: [Maybe Node]
nodeColor      :: Node -> Maybe Color

现在我想将颜色映射到节点,作为中间步骤,我想要一个元组列表:

coloredList    :: [(Color, [Node])]

(因为稍后我将使用 listToUFM_C (++) listColored 构建一个 map )

这是我到目前为止所拥有的,它有效但看起来很丑:

listColored    =  mapMaybe (\n -> nodeColor n >>= \c -> Just (c, [n])) $ catMaybes maybeNeighbors

(使用 Data.Maybe 中的 catMaybesmapMaybe)

我觉得我错过了一些东西,我应该能够做类似 (fmap . fmap) func maybeNeighbors 的事情,但我不知道如何 func应该看起来像。 或者像这样的函数,我也找不到:(Maybe a -> Maybe b) -> [Maybe a] -> [Maybe b]

编辑:

我正在解决图形着色问题,我想要一个具有相同颜色的节点列表。以下是在 GHCi 中测试的示例:

let l = [Just (1, Just 'a'), Just (2, Just 'a'), Nothing, Just (3, Just 'b'), Just (4, Nothing)]

最佳答案

这似乎是最干净的列表理解:

listColored = 
    [ (c, [n])
    | Just n <- maybeNeighbors
    , Just c <- [nodeColor n]
    ]

在列表理解中,模式匹配失败将导致跳过该元素,因此您自然会删除 maybeNeighbors 中的 Nothing 以及nodeColor 输出 Nothing

关于haskell - 使用 Maybe 返回函数映射和过滤 Maybe 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62539445/

相关文章:

java - 用 Optional.ofNullable(...).ifPresent(...) 替换 get/test/set of bare references?

swift - 当 ElementOfResult 被推断为 Optional 时,flatMap 不会过滤掉 nil

haskell - 如何设置 IntelliJ 以使用 Stack 构建 Haskell 项目?

scala - 是否可以将类型构造函数视为函数式编程语言中的类型?

haskell - 我将如何以无点风格编写此函数?

scala - 术语 "reason about"在计算机科学中意味着什么?

java - 为什么使用 Optional.of 而不是 Optional.ofNullable?

haskell - 如何获取函数类型定义中声明的枚举类型的最小值?

function - 如何在 Swift 中创建 _inline_ 递归闭包?

go - 如何实现 Python functools.wraps 等效?