首页 > 解决方案 > Haskell 中的 Where 子句使用 Data.Map

问题描述

我在 Haskell 的一个特定场景中有一个小问题。

我的图表:

import Data.Map (Map,empty,member,insert,keys,findWithDefault,assocs ,fromList,(!),union,mapWithKey,adjust)
import Graphviz

-- | A directed graph
data Graph v = Graph
    { arcsMap :: Map v [v]     -- A map associating a vertex with its successors
    , labelMap :: Map v String -- The Graphviz label of each node
    , styleMap :: Map v String -- The Graphviz style of each node
    }

我的功能:

-- | Replaces the labels of each vertex by an empty string
--
-- >>> g = addArcs emptyGraph [(1,2),(2,3),(1,3)]
-- >>> putStrLn $ graphvizString $ unlabelGraph g
-- digraph {
--     1 [label=""];
--     2 [label=""];
--     3 [label=""];
--     1 -> 2;
--     1 -> 3;
--     2 -> 3;
-- }
-- ...
unlabelGraph :: Ord v => Graph v -> Graph v
unlabelGraph  (Graph arcs labels styles)= (Graph arcs (mapWithKey f labels ) styles)
                                         where f  = adjust "" *the actual key*

我想达到地图标签的每个值以用“”替换它们。如何在函数的 where 子句中指定我想要 Map 的键?这是编写此函数的最佳方法吗?

标签: haskellgraphfunctional-programming

解决方案


这应该有效:

import qualified Data.Map as M

unlabelGraph  (Graph arcs labels styles) =
   (Graph arcs (M.mapWithKey f labels) styles)
   where f _key _value = ""

不过,您实际上并不需要 中的密钥f,因为它总是会返回空字符串。因此,我们可以使用

unlabelGraph  (Graph arcs labels styles) =
   (Graph arcs (M.map f labels) styles)
   where f _value = ""

甚至

unlabelGraph  (Graph arcs labels styles) =
   (Graph arcs (M.map (const "") labels) styles)

甚至

unlabelGraph g = g{labelMap = M.map (const "") (labelMap g)}

推荐阅读