cybertextron
cybertextron

Reputation: 10981

Duplicate instance declarations - Haskell

I have the following type in Haskell:

data Cplx = Cplx Float Float deriving (Eq, Ord, Show)

instance Ord Cplx where 
    (<=) (Cplx x1 y1) (Cplx x2 y2) = compare(sqrt(abs(x1*x1) + abs(y1*y1)), sqrt(abs(x2*x2) + abs(y2*y2)))

Because Complex numbers are ordered not by its actual values, but rather by the abs values for r and i, I'm trying to define <= for the Cplx type. However, When i load my type Cplx in ghci, I get:

test.hs:1:44:
    Duplicate instance declarations:
      instance Ord Cplx -- Defined at test.hs:1:44
      instance Ord Cplx -- Defined at test.hs:3:10
Failed, modules loaded: none.

After changing the Declaration to :

data Cplx = Cplx Float Float deriving (Eq, Show)

I now get:

Couldn't match expected type ‘Bool’
            with actual type ‘(Float, Float) -> Ordering’
Probable cause: ‘compare’ is applied to too few arguments
In the expression:
  compare
    (sqrt (abs (x1 * x1) + abs (y1 * y1)), 
     sqrt (abs (x2 * x2) + abs (y2 * y2)))
In an equation for ‘<=’:
    (<=) (Cplx x1 y1) (Cplx x2 y2)
      = compare
          (sqrt (abs (x1 * x1) + abs (y1 * y1)), 
           sqrt (abs (x2 * x2) + abs (y2 * y2)))

Upvotes: 0

Views: 1302

Answers (1)

jwodder
jwodder

Reputation: 57610

data Cplx = ... deriving (..., Ord, ...) causes an Ord instance to be automatically derived for Cplx which conflicts with the explicit instance you give later. Change the deriving expression to just deriving (Eq, Show).

EDIT: Your second problem is that this part:

compare(sqrt(abs(x1*x1) + abs(y1*y1)), sqrt(abs(x2*x2) + abs(y2*y2)))

is wrong. You're passing a (Float, Float) pair to compare rather than two separate Float arguments. Remove the comma and adjust the parentheses accordingly:

compare (sqrt (abs (x1*x1) + abs (y1*y1))) (sqrt (abs (x2*x2) + abs (y2*y2)))

Upvotes: 6

Related Questions