Superian007
Superian007

Reputation: 395

Haskell: Show recursive data type

I have a custom recursive data type

data Vertex = Vertex Int [Vertex]

where Int is an index number of the vertex and [Vertex] are vertices adjacent to this vertex.

Now, I want to show this data type as a list of indexes of vertices: Let's say there are two vertices a and b with indexes 1 and 2 respectively and they are adjacent to each other. My output should look like this: "[(1, [2])]".

I figured out that I must write an instance of Show for Vertex. And here is my problem, how can I show recursive data type? I think Haskell's laziness might be the solution?

EDIT - Example

As I mentioned above I have Vertex data type. Now, I have an adjacency list with vertices and their adjacent vertices:

adjacencyList :: [Vertex]
adjacencyList = [a, b, c]
 where a = Vertex 6 [b]
       b = Vertex 7 [a, c]
       c = Vertex 12 [b]

When I write this

print adjacencyList

I would like to have output that looks like this:

[(6, [7]), (7, [6, 12]), (12, [7])]

Upvotes: 0

Views: 201

Answers (1)

Cactus
Cactus

Reputation: 27636

If you just need direct adjacency, then recursiveness is not really an issue, since you can just do

toAdjacency :: [Vertex] -> [(Int, [Int])]
toAdjacency = map outFrom
  where
    outFrom (Vertex i vs) = (i, map inTo vs)
    inTo (Vertex i _) = i

Then show . toAdjacency is exactly the format you are after.

Upvotes: 1

Related Questions