0

Below I give data constructors for list and trees.

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

With these definitions I can create infinite structures easily as shown below:

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

I want to create infinite graphs (both directed and undirected) in this manner. How to declare a data constructor for it and how to create an infinite graph using that data constructor in Haskell?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Tem Pora
  • 1,913
  • 2
  • 21
  • 29

1 Answers1

1

A simple solution is to use some form of indirection, like indices

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

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

However this isn't quite as satisfying as knot tying

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..]

We map Vertex over [1..] which gives us a list of functions [Vertex] -> Vertex which want a list of edges to connect each vertex to. Since infGraph is the list of all vertices, we pass that to each Vertex and tie the knot.

Of course for serious work, use a package.

Daniel Gratzer
  • 49,751
  • 11
  • 87
  • 127
  • In the second one, you gave `type Graph = [Vertex]`, I didn't not understand how do you get the edges from this thing? please explain it. – Tem Pora Nov 04 '13 at 16:11
  • @TemPora Look at the definition of vertices, the edges are embedded in the vertices. – Daniel Gratzer Nov 04 '13 at 16:12
  • Thanks. I had saw the previous definition for it. Got confused how Integer can handle all this things. Sorry. – Tem Pora Nov 04 '13 at 16:16
  • @TemPora No problem, does this answer your question? – Daniel Gratzer Nov 04 '13 at 16:19
  • It seems to work but I not understand how the magic happening in the `map (flip Vertex infGraph) [1..]`. Can you explain a bit about how and why the map is used? – Tem Pora Nov 04 '13 at 16:21
  • Thanks. You write: `-- Construct a graph of infinitely many vertices in which -- each vertex is connected.` Is it do you mean, `--each vertex is connected to all the vertices`? – Tem Pora Nov 04 '13 at 16:47
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/40522/discussion-between-tem-pora-and-jozefg) – Tem Pora Nov 04 '13 at 18:45