gpt4 book ai didi

Haskell Data.Graph graphFromEdges 示例

转载 作者:行者123 更新时间:2023-12-01 20:26:54 25 4
gpt4 key购买 nike

我目前正在尝试为 Haskell 编写一个 GraphML 阅读器(请参阅 this previous question )。由于我对 Haskell 还很陌生,尽管学习曲线陡峭,但我还没有完全学会仅从 Hackage 文档中推导出示例的能力。

我当前拥有的是一个 Graph 实例:

data Graph = Graph
{ graphId :: String,
nodes :: [String],
edges :: [(String, String)] -- (Source, target)
}
deriving (Show, Eq)

我想将它们转换为 Data.Graph 。我认为 graphFromEdgesgraphFromEdges' 是执行此操作的正确函数。

我当前的尝试是创建三元组(nodeid,nodeid,[边缘目标])

-- Convert a graph node into a Data.Graph-usable
getDataGraphNode :: Graph -> String -> (String, String, [String])
getDataGraphNode graph node = (node, node, getTargets node graph)

-- Convert a Graph instance into a Data.Graph list of (node, nodeid, edge) tuples
getDataGraphNodeList :: Graph -> [(String, String, [String])]
getDataGraphNodeList graph = map (getDataGraphNode graph) (nodes graph)

但是,由于类型错误,GHC 不会编译它:

 Couldn't match expected type `[(node0, key0, [key0])]'
with actual type `(String, String, [String])'

您能否给我指出一个示例,或者最好描述一下如何从文档中推导出示例的一般方法(在本例中为函数签名)?我是否需要使用 Data.Graph 中的 Vertex 类型?我目前无法弄清楚 node0key0 类型需要是什么。

这是一个最小的示例,显示了我在使用 Data.Graph 时遇到的问题。我不确定这与误用类型有何关系,即使我自己的代码中的许多错误是由于类型系统问题而发生的:

import Data.Graph
main = do
graph <- graphFromEdges' [("n0","n0",["n1"]), ("n1","n1",["n2"]), ("n2","n2",[])]
-- This should print ["n0","n1","n2"]
print $ vertices graph

它会产生以下错误消息:

bar.hs:4:5:
Couldn't match type `IO' with `(,) Graph'
Expected type: (Graph, ())
Actual type: IO ()
In a stmt of a 'do' block: print $ vertices graph
In the expression:
do { graph <- graphFromEdges'
[("n0", "n0", ["n1"]), ("n1", "n1", ["n2"]), ....];
print $ vertices graph }
In an equation for `main':
main
= do { graph <- graphFromEdges' [("n0", "n0", [...]), ....];
print $ vertices graph }

bar.hs:4:22:
Couldn't match type `Vertex -> ([Char], [Char], [[Char]])'
with `GHC.Arr.Array Vertex [Vertex]'
Expected type: Graph
Actual type: Vertex -> ([Char], [Char], [[Char]])
In the first argument of `vertices', namely `graph'
In the second argument of `($)', namely `vertices graph'
In a stmt of a 'do' block: print $ vertices graph

最佳答案

试试这个:

import Data.Graph
main = do
let (graph, vertexMap) = graphFromEdges' [("n0","n0",["n1"]), ("n1","n1",["n2"]),("n2","n2",[])]
-- This should print ["n0","n1","n2"]
print $ map ((\ (vid, _, _) -> vid) . vertexMap) (vertices graph)

graphFromEdges' 返回一对值和 Graph是那对中的第一个。另外,在这种情况下<-用于返回 IO something 的东西而graphFromEdges'返回一个纯值。

关键错误是这样的:

Couldn't match type `IO' with `(,) Graph'
Expected type: (Graph, ())
Actual type: IO ()

虽然报告的方式有点误导 - 如果您给出main,报告会更好类型签名 main :: IO () 。一般来说,如果您对类型错误感到困惑,那么值得尝试找出您认为事物应该是什么类型并使用显式类型签名。

关于Haskell Data.Graph graphFromEdges 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21192423/

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