Search code examples
haskelldata-structuresgraphedges

Building a graph from a list of edges


Given a graph datatype as follows:

data Graph = Int :~> [Graph]
infixr :~>

and a list of edges like this:

edges = [(10,1), (10,5), (1,2), (2,3), (5,6), (5,9), (9,8)]

What is the function that will build the graph as follows:

result = 10 :~> [ 1 :~> [ 2 :~> 3 :~> [] ] 
                , 5 :~> [ 6 :~> [], 9 :~> 8 :~> [] ]
                ]

I'm sure it's right in front of my head, but I'm a bit exhausted and would appreciate the help. Thanks!


Solution

    1. Find the start node: The node appears in the map fst edges list but not in the map snd edges list. As luqui remarked, you need to think about cases where you don't find such a node (or if you find more than one)
    2. Build your tree recursively from this start node. Be careful as you could still have cycles in the graph