Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining own Ord for a data type

I am attempting to make some data structures to solve a graph puzzle. I am trying to define an edge's comparison criteria, but I am not sure how. So far:

data Edge = Edge (Set String) Bool 

How can I 'inform' the compiler that I want edges to be declared equal if they have identical sets of strings, and not have equality have anything to do with the boolean value?

like image 213
Mantas Vidutis Avatar asked Jun 17 '10 21:06

Mantas Vidutis


People also ask

What data type is Ord?

Documentation. The Ord class is used for totally ordered datatypes. Instances of Ord can be derived for any user-defined datatype whose constituent types are in Ord . The declared order of the constructors in the data declaration determines the ordering in derived Ord instances.

How do you define a data type in Haskell?

The Data Keyword and Constructors In general, we define a new data type by using the data keyword, followed by the name of the type we're defining. The type has to begin with a capital letter to distinguish it from normal expression names. To start defining our type, we must provide a constructor.

How do types work in Haskell?

In Haskell, every statement is considered as a mathematical expression and the category of this expression is called as a Type. You can say that "Type" is the data type of the expression used at compile time.


1 Answers

Although I'm not sure why you want to ignore the boolean value (I'm curious), to do so you'll have to define your own Eq instance; the default one won't work, as it compares every field. Luckily, this is easy:

instance Eq Edge where   (Edge s1 _) == (Edge s2 _) = s1 == s2 

If you want to be able to order edges, and you want the ordering to compare just the sets too, your implementation is very similar:

instance Ord Edge where   (Edge s1 _) `compare` (Edge s2 _) = s1 `compare` s2 

Each type class defines a certain set of methods which need to be implemented; Eq requires == or /=, and Ord requires <= or compare. (To find out which functions are required and which are optional, you can check the docs.)

like image 145
Antal Spector-Zabusky Avatar answered Sep 23 '22 01:09

Antal Spector-Zabusky