0

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)))
1
  • 1
    as a side note: there is no linear ordering on Complex numbers (en.wikipedia.org/wiki/Complex_number#Ordering) as you can se easily for the one you gave: (1,0) <= (0,1) and (0,1) <= (1,0) but of course they are not equal Commented Oct 13, 2014 at 6:32

1 Answer 1

6

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)))
Sign up to request clarification or add additional context in comments.

1 Comment

I've added the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.