Haskell中的非法实例声明

时间:2018-11-29 07:00:38

标签: haskell compiler-errors typeclass

我尝试了以下代码

class Group a where
  (.+.) :: a -> a -> a
  (.-.) :: a -> a -> a
  zero :: a
  opposite :: a -> a

  x .-. y = x .+. opposite y
  opposite x = zero .-. x
  {-# MINIMAL (.+.), zero, (opposite | (.-.)) #-}

instance Fractional a => Group a where
  x .+. y = x + y
  zero = 0 :: a
  opposite = negate :: a -> a

但是在加载到GHCi中时,出现以下错误:

group1.hs:11:26: error:
    • Illegal instance declaration for ‘Group a’
        (All instance types must be of the form (T a1 ... an)
         where a1 ... an are *distinct type variables*,
         and each type variable appears at most once in the instance head.
         Use FlexibleInstances if you want to disable this.)
    • In the instance declaration for ‘Group a’
   |
11 | instance Fractional a => Group a where
   |    

我在做什么错了?

2 个答案:

答案 0 :(得分:3)

啊!我终于明白了,出什么事了。在Haskell中,只能为ADT实例化一个类。因此,唯一合理的解决方案是声明以下内容:

class Group a where
  (.+.) :: a -> a -> a
  (.-.) :: a -> a -> a
  zero :: a
  opposite :: a -> a

  x .-. y = x .+. opposite y
  opposite x = zero .-. x
  {-# MINIMAL (.+.), zero, (opposite | (.-.)) #-}

newtype GroupType a = GroupType a  

instance Fractional a => Group (GroupType a) where
  GroupType x .+. GroupType y = GroupType $ x + y
  zero = GroupType 0
  opposite (GroupType x) = GroupType $ negate x

答案 1 :(得分:1)

我能够编译您的示例:

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}

class Group a where
  (.+.) :: a -> a -> a
  (.-.) :: a -> a -> a
  zero :: a
  opposite :: a -> a

  x .-. y = x .+. opposite y
  opposite x = zero .-. x
  {-# MINIMAL (.+.), zero, (opposite | (.-.)) #-}

-- data Fractional a = Fractional a a

instance (Fractional a, Num a) => Group a where
  x .+. y = x + y
  zero = 0
  opposite = negate
  • FlexibleInstances允许带有约束的未知类型的实例。基本上允许instance X a
  • 我们需要的
  • UndecidableInstances是因为我们声明任何a都属于类Group,并且它可能(不可避免地)导致a属于Group几个不同的instance声明。