重复的实例声明 - Haskell

时间:2014-10-12 23:17:22

标签: 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)))

因为复数不按实际值排序,而是按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.

将声明改为:

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

我现在得到:

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 个答案:

答案 0 :(得分:6)

data Cplx = ... deriving (..., Ord, ...)导致为Ord自动派生Cplx实例,该实例与您稍后提供的显式实例冲突。将deriving表达式更改为deriving (Eq, Show)

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

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

错了。您已将(Float, Float)对传递给compare而不是两个单独的Float参数。删除逗号并相应地调整括号:

compare (sqrt (abs (x1*x1) + abs (y1*y1))) (sqrt (abs (x2*x2) + abs (y2*y2)))
相关问题