Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: overloading == for graph ADT

I have a declaration of graph for which I need to overload "==" operator in Haskell (problem from the book).

data Node a = Node {
label :: a,
adjacent :: [(a,Int)]
} deriving Show

data Network a = Graph [Node a] deriving Show

Basically, two graphs are equal if they have same vertices and edges (but Node's may be in different order in Network data type as well as list of adjacent vertices in Node data type). Have some difficulties in that, any help will be appreciated.

Thanks in advance.

NOTE: My problem is with the equality check, not with the syntax of making instances of type classes.

like image 647
Kudayar Pirimbaev Avatar asked Apr 24 '26 00:04

Kudayar Pirimbaev


1 Answers

If you can't just use deriving (Eq, Show) then you have to implement it by hand.

instance (Eq a) => Eq (Node a) where
    n1 == n2 = (* Implement the equality check here *)

instance (Eq a) => Eq (Network a) where
    g1 == g2 = (* Implement the equality check here *)

This is really what that derive statement does for you automatically.

If you want more on typeclasses, I like Learn you a Haskell's explanation.

If you want help on actual equality checks, use Data.Map with the fromList function.

As for the nodes, this snippet should do it

(==) = (==) `on` label

or to be more explicit

n1 == n2 = label n1 == label n2
like image 84
Daniel Gratzer Avatar answered Apr 26 '26 14:04

Daniel Gratzer