haskell - 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 的键?这是编写此函数的最佳方法吗?
解决方案
这应该有效:
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)}
推荐阅读
- image-processing - Hough transformation calculation
- pandas - 水平聚合数据框
- amazon-web-services - Blocking all traffic except from ELB security groups, nginx responds with 502
- c# - 约瑟夫斯幸存者
- angular - IONIC 5 空 FormData
- c++ - 如何从标头确定有效负载大小?
- python - 使用 Python selenium-requests,如何传递查询字符串参数?
- python - 如何解决此 python 代码中缺少 1 个必需的位置参数?
- sql - Hive查询:根据条件选择一列,另一列值匹配某些特定值,然后将匹配结果创建为新列
- java - 无法从 powershell 创建和运行 JAR 文件