重复的实例声明 - Haskell

cyb*_*ron 0 haskell

我有以下类型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)))
Run Code Online (Sandbox Code Playgroud)

因为复数不按实际值排序,而是按r和i的abs值排序,我试图<=为Cplx类型定义.但是,当我在ghci中加载我的类型Cplx时,我得到:

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.
Run Code Online (Sandbox Code Playgroud)

将声明改为:

data Cplx = Cplx Float Float deriving (Eq, Show)
Run Code Online (Sandbox Code Playgroud)

我现在得到:

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)))
Run Code Online (Sandbox Code Playgroud)

jwo*_*der 6

data Cplx = ... deriving (..., Ord, ...)导致Ord实例自动派生,Cplx与之后给出的显式实例发生冲突.将deriving表达式更改为just deriving (Eq, Show).

编辑:你的第二个问题是这部分:

compare(sqrt(abs(x1*x1) + abs(y1*y1)), sqrt(abs(x2*x2) + abs(y2*y2)))
Run Code Online (Sandbox Code Playgroud)

是错的.你传递的是(Float, Float)一对compare而不是两个单独的Float参数.删除逗号并相应地调整括号:

compare (sqrt (abs (x1*x1) + abs (y1*y1))) (sqrt (abs (x2*x2) + abs (y2*y2)))
Run Code Online (Sandbox Code Playgroud)