2013-11-04 100 views
0

下面我给出了列表和树的数据构造函数。如何声明图的数据构造函数

data List a = NilL | Cons a (List a) deriving Show 
data Tree a = NilT | Branch a [Tree a] deriving Show 

利用这些定义我可以轻松地创建无限结构,如下所示:

list = Cons 1 list 
tree = Branch 1 lt 
where 
    lt = tree : lt 

我想创建以这种方式无限的曲线图(包括定向和非定向)。如何为它声明数据构造函数以及如何使用Haskell中的数据构造函数创建无限图?

+0

您可能还喜欢[“您如何在Haskell中表示图形?”](http://stackoverflow.com/q/9732084/791604)。 –

回答

1

一个简单的解决方案是使用某种形式的间接的,如指数

type Vertex = Integer 
data Graph = Graph [Vertex] [(Vertex, Vertex)] 

infGraph = Graph [1..] [(a, b) | a <- [1..], b <- [1..]] 

然而,这并不像打结

data Vertex = Vertex { tag :: Integer 
        , edges :: [Vertex] } 

type Graph = [Vertex] -- A graph is determined by the set of vertices 

-- Construct a graph of infinitely many vertices in which 
-- each vertex is connected. 
infGraph = map (flip Vertex infGraph) [1..] 
infGraph' = map (\v' -> v' infGraph') . map Vertex $ [1..] 

我们mapVertex[1..]这给了我们为满足函数列表[Vertex] -> Vertex,它们需要一列边来连接每个顶点。由于infGraph是所有顶点的列表,我们将其传递给每个Vertex并打结。

当然对于认真的工作,请使用package

+0

在第二个例子中,你给了'type Graph = [Vertex]',我不明白你是如何从这件事物中获得优势的?请解释一下。 –

+0

@TemPora看看顶点的定义,边被嵌入顶点。 – jozefg

+0

谢谢。我已经看到了它的先前定义。弄糊涂了Integer如何处理所有这些事情。抱歉。 –

相关问题