I just started using Haskell some weeks ago and I lack of imagination to resolve a function in this situation.
So I am trying to find the predecessors of a vertex in a graph implemented in Haskell.
My graph :
-- | A directed graph
data Graph v = Graph
{ arcsMap :: Map v [v] -- A map associating a vertex with its successors
, labelMap :: Map v String -- The Graphviz label of each node
, styleMap :: Map v String -- The Graphviz style of each node
}
The function successors
:
-- | Returns the successors of a vertex in a graph in ascending order
--
-- We say that `v` is a successor of `u` in a graph `G` if the arc `(u,v)`
-- belongs to `G`.
-- Note: Returns the empty list if the vertex does not belong to the graph.
successors :: Ord v => v -> Graph v -> [v]
successors v (Graph arcs _ _) = findWithDefault [] v arcs
And the function I'm currently trying to resolve :
-- | Returns the predecessors of a vertex in a graph in ascending order
--
-- We say that `u` is a predecessor of `v` in a graph `G` if the arc `(u,v)`
-- belongs to `G`.
-- Note: Returns the empty list if the vertex does not belong to the graph.
predecessors :: Ord v => v -> Graph v -> [v]
predecessors v (Graph arcs _ _) =
map (fst) (filter (\(x,[y]) -> elem v [y]) (assocs arcs) )
I need to find a way to get the keys (the vertices) by having the value (the successor) of those vertices. For example :
-- >>> predecessors 3 $ addArcs emptyGraph [(1,2),(2,3),(1,3)]
-- [1,2]
But when I run that line, I get Non-exhaustive patterns in lambda.
What is that and how can I fix it? Thank you!
- Edit : Never mind I corrected it but I still do not really understand how haha