将图形更改为Haskell中的节点列表
我有以下数据类型:将图形更改为Haskell中的节点列表,haskell,graph,Haskell,Graph,我有以下数据类型: data Node a = Node { label :: a, adjacent :: [(a,Int)] } deriving Show data Network a = Graph [Node a] deriving Show 我想把一个图变成一个节点列表。例如,我想将此转换为: Graph [ ( Node 'a' [ ( 'b' , 3 ) , ( 'c' ,2 ) ] ) , ( Node 'b' [ ('c' , 3 ) ] ) , (
data Node a = Node
{ label :: a,
adjacent :: [(a,Int)] } deriving Show
data Network a = Graph [Node a] deriving Show
我想把一个图变成一个节点列表。例如,我想将此转换为:
Graph [ ( Node 'a' [ ( 'b' , 3 ) , ( 'c' ,2 ) ] ) , ( Node 'b' [ ('c' , 3 ) ] ) , ( Node 'c' [] ) ]
为此:
[ ( Node 'a' [ ( 'b' , 3 ) , ( 'c' ,2 ) ] ) , ( Node 'b' [ ('c' , 3 ) ] ) , ( Node 'c' [] ) ]
我编写了这个函数和它的一些其他变体:
deGraph Graph [Node x y] = [Node x y]
但我总是犯错误。你能告诉我该如何改变我的功能吗?
谢谢。您误解了如何在列表中进行模式匹配
foo [x] = x
匹配单个元素的列表并将该元素绑定到x
因为您希望它在所有列表中都匹配,所以您可以执行以下操作
foo xs = xs
因此,您的代码应该更改为
deGraph (Graph nodes) = nodes
-- Notice the fact that I wrapped the constructor
-- in parens
总结:
为了明确起见,以下是您可以在列表中进行匹配的不同方式
-- matches on individual elements (this is syntactic sugary goodness)
foo [x, y] = x
-- grabs the head and tail of the list (This is actual deconstructing)
foo (x:rest) = x
-- matches an empty list
foo [] = error "Oh noes"
-- matches everything
foo xs = head xs
或者上述任何组合。您误解了如何在列表中进行模式匹配
foo [x] = x
匹配单个元素的列表并将该元素绑定到x
因为您希望它在所有列表中都匹配,所以您可以执行以下操作
foo xs = xs
因此,您的代码应该更改为
deGraph (Graph nodes) = nodes
-- Notice the fact that I wrapped the constructor
-- in parens
总结:
为了明确起见,以下是您可以在列表中进行匹配的不同方式
-- matches on individual elements (this is syntactic sugary goodness)
foo [x, y] = x
-- grabs the head and tail of the list (This is actual deconstructing)
foo (x:rest) = x
-- matches an empty list
foo [] = error "Oh noes"
-- matches everything
foo xs = head xs
或以上任意组合。感谢您的回复。我已经尝试了
deGraph(Graph nodes)=nodes
,它给了我这个错误:Main>deGraph[(Node'a'[('b',3),('c',2)],(Node'b'[('c',3)],(Node'c'[)]应用程序表达式中的错误类型:deGraph[Node'a'[('b',3),(c',2)],Node'b'[('c',Term:[Node'a'[('b',3),('c',2)],节点'b'[('c',3)],节点'c'[]类型:[Node Char]不匹配:网络aThat's因为你忘了包装在图构造函数中,你刚刚传入了节点的原始列表,现在它给出了这个:Main>deGraph图[(节点'a'[('b',3),('c',2)],(节点'b'[('c',3)]),(节点“c”[])]应用程序中的错误类型***表达式:deGraph图形[节点“a”[(“b”,3),(“c”,2)],节点“b”[(“c”,3)],节点“c”[]***术语:deGraph***类型:网络d->[节点d]***不匹配:a->b->CY您需要确保您的优先级正确,您需要在构造函数调用周围设置参数您能解释一下您最后说的内容吗?谢谢您的回复。我已经尝试了deGraph(Graph nodes)=nodes
,它给了我以下错误:Main>deGraph[(Node'a'[('b',3),('c',2)],(节点'b'[('c',3)],(节点'c'[])应用程序表达式中的错误类型:deGraph[Node'a'[('b',3),('c',2)],Node'b'[('c',3)],Node'c'[]术语:[Node'a'[('b',3),('c',2)],Node'b'[('c',3)],Node'c'[]类型:[Node'c'[]不匹配:网络aThat是因为你忘了包装在图
构造函数中,你刚刚传入了节点
s的原始列表,现在它给出了:Main>deGraph图[(节点'a'[('b',3),('c',2)],(节点'b'[('c',3)],(节点'c'[])]错误-应用程序中的类型错误***表达式:deGraph图形[节点'a'[('b',3),('c',2)],节点'b'[('c',3)],节点'c'[]***术语:deGraph***类型:网络d->[节点d]***不匹配:a->b->C您需要确保您的优先级是正确的,您需要在构造函数调用周围设置参数您能再解释一下您最后说的话吗?