我尝试了以下代码
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/