for an exercise I need to reverse a graph (reverse all edges), but I don't get anywhere. So I need some help.
I am aware you might not want to solve the exercise for me, so that's not what I am asking for. I just need to get some advice...
So to get to it:
data Graph a = G
{ nodes :: [a]
, successors :: a -> [a] }
reverseGraph :: Eq a => Graph a -> Graph a
A graph has to parameters: a list of nodes and a function that defines the successors. This function has the type:
a -> [a]
for example:
graph1 :: Graph Int
graph1 = G [1..6] $ \case 1 -> [2,3]
2 -> []
3 -> [1,4,6]
4 -> [1]
5 -> [3,5]
6 -> [2,4,5]
the reversed graph would be:
reverseGraph graph1 ~>
2 -> [1,6]
3 -> [1,5]
1 -> [3,4]
4 -> [3,6]
6 -> [3]
5 -> [5,6]
I get that I need to check for each node in the input graph the successors and add for each the input node to the new successor list of the output node.
But i just don't get how to do this in Haskell.
Any help is appreciated!
Here is my solution for anyone who may attempt something similar:
reverseGraph :: Eq a => Graph a -> Graph a
reverseGraph (G nodes sucs) = (G nodes sucs') where
sucs' a = getVert a nodes sucs
--Makes a list of all occurrences of v in the succeccor list.
getVert :: Eq a => a -> [a] -> (a-> [a]) -> [a]
getVert v [] succs = []
getVert v (n:ns) succs = if v `elem` succs n then [n]++getVert v ns succs else getVert v ns succs
[n] ++ ...is much better written asn : ....reverseGraph, namely the fact that it has only anEq aconstraint, forces you to use a very inefficient implementation. If you had a constraint ofOrd aor(Eq a, Hashable a), then you could do considerably better.