haskell - Haskell中的非法实例声明

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

我究竟做错了什么?

最佳答案

我能够编译您的示例:

{-# 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
  • 关于haskell - Haskell中的非法实例声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53533481/

    相关文章:

    haskell - 如何从 "add"的类 "Add"打印函数 "Fun with Type Functions"的结果

    haskell - 为什么类型类难以实现?

    haskell - 管理约束爆炸 (Haskell)

    haskell - 如何 `List + List = List[List]]`

    compiler-errors - “'附近” : syntax error

    在 GCC 中编译而不生成输出文件

    Haskell Typeclass 类型约束和推导

    haskell - 如何在 Haskell 递归调用中打印迭代?

    haskell - Haskell可以建模吗?

    c# - C# 中的三元运算符