将图形更改为Haskell中的节点列表 [英] Changing a graph to list of nodes in Haskell
问题描述
数据节点a =节点
{label :: a,
adjacent :: [(a,Int)]}派生Show
data Network a = Graph [Node a]派生Show
我想将图形转换为节点列表。例如,我想打开它:
$ $ $ $ $ $ $ $ $ $ c',2)]),(Node'b'[('c',3)]),(Node'c'[])]
改为:
[(Node'a'[('b' ,('c',2)]),(Node'b'[('c',3)]),(Node'c'[])]
我写了这个函数和其他一些变体:
deGraph图形[节点xy] = [节点xy]
但是我不断收到错误。你能告诉我如何改变我的功能吗?
谢谢。解决方案
foo [x] = x
匹配单个元素的列表并将该元素绑定到x。
因为您希望它匹配所有列表,所以您可以执行类似于
foo xs = xs
所以你的代码应该改成
deGraph(图形节点)=节点
- 注意事实我包装了构造函数
- 在parens中
总结:
只要明确一点,以下是您可以在列表中匹配的不同方式
- 匹配单个元素(这是句法含义)
foo [x,y] = x
- 抓取列表的头部和尾部(这是实际的解构)
foo (x:rest)= x
- 匹配一个空列表
foo [] =错误Oh noes
- 匹配一切
foo xs =头部xs
或者上述的任意组合。 / p>
I have these data types :
data Node a = Node { label :: a, adjacent :: [(a,Int)] } deriving Show data Network a = Graph [Node a] deriving Show
I want to turn a graph to a list of nodes. For example I want to turn this :
Graph [ ( Node 'a' [ ( 'b' , 3 ) , ( 'c' ,2 ) ] ) , ( Node 'b' [ ('c' , 3 ) ] ) , ( Node 'c' [] ) ]
to this :
[ ( Node 'a' [ ( 'b' , 3 ) , ( 'c' ,2 ) ] ) , ( Node 'b' [ ('c' , 3 ) ] ) , ( Node 'c' [] ) ]
I wrote this function and some other variations of it :
deGraph Graph [Node x y] = [Node x y]
but I kept getting erros. Can you tell me how I should change my function? Thanks.
解决方案You're misunderstanding how to pattern match on a list.
foo [x] = x
matches a list of a single element and binds that element to x.
Since you want it to match on all lists, you'd do something like
foo xs = xs
so your code should change to
deGraph (Graph nodes) = nodes -- Notice the fact that I wrapped the constructor -- in parens
Wrap up:
Just to be explicit, here are the different ways you can match on a list
-- 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
Or any combination of the above.
这篇关于将图形更改为Haskell中的节点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文