映射和过滤具有可能返回函数的可能列表

Mapping and filtering a list of maybes with a maybe returning function

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

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 和 [=11= 中删除 Nothings ] 来自 nodeColor.

的输出

如果我没理解错的话,你是在做一个函数[Maybe Node] -> Map Color [Node]?

colorMap :: [Maybe Node] -> Map Color [Node]
colorMap = Map.fromListWith (++) . listColored

listColored :: [Maybe Node] -> [(Color, [Node])]
listColored = mapMaybe $ \maybeNode -> do
  node <- maybeNode
  color <- nodeColor node
  pure (color, [node])

编辑: 分离出 listColored 部分以便更好地与 Fyodor 的列表理解进行比较。