Krismu
Krismu

Reputation: 503

Defining Ord instance for own datatype

Being new to Haskell I am having trouble to get an Order instance implemented for my datatype, namely:

data Polynom = Polynom ([Double])
deriving Show   
p0 = Polynom([3.9,4.2,2.7])
p1 = Polynom([0.0,0.2,-3.6,9.4])

Polynomes are being a list of doubles, where i.e. p0 = 2.7x² + 4.2x + 3.9. My problem is that I just couldn't figure out the correct syntax for declaring the various if-cases, starting something like:

instance Ord Polynom where
realLength(a) > realLength(b) = a > b
       where if realLength(a)) == realLength(b) = compare lastElement(a) lastElement(b)

I know this is a really bad pseudo-code, but I hope you get the idea.

I would really appreciate any hints on how to get started, I think I can figure out the different cases myself!

Edit: Figured instance Eq could be something like that, but compiler does not accept it.

instance Eq Polynom where
(realPolynom a) == (realPolynom b) = (Polynom a) == (Polynom b)

Code for realPolynom:

realPolynom :: Polynom -> Polynom
realPolynom (Polynom(m:ns)) 
| m==0.0 = realPolynom (Polynom(ns))
| otherwise = Polynom(m:ns)

Upvotes: 0

Views: 1353

Answers (1)

chi
chi

Reputation: 116139

You may be looking for

instance Ord Polynom where
  compare (Polynom p) (Polynom q) = compare (length p, reverse p) (length q, reverse q)

this compares polynomials first by length (degree). When lengths coincide, coefficients are compared.

Note that this assumes the first coefficient (last in the list) of a polynomial is non-null. That is, Polynomial [0,1,0] is greater thanPolynomial [0,2] according to this ordering. You may wish to add a dropWhile (==0) to cope with this.

Upvotes: 3

Related Questions