我正在尝试为有符号数字类型制作一个类型类。这是我的代码:
{-# LANGUAGE TypeFamilies, FlexibleContexts, UndecidableInstances #-}
data Sign = Negative | Zero | Positive
deriving (Eq, Ord, Read, Show)
class Signed a where
sign :: a -> Sign
instance Signed Integer where
sign = undefined
这可以编译,但我想调整此代码以适用于任何Integral a
。
instance (Integral a) => Signed a where
sign = undefined
此时它无法编译。
我已经检查了具有类型约束的 Haskell 类型系列实例,但这似乎正在解决与我的不同的问题。我不认为我的代码中存在语法错误。
尝试编译代码会产生以下错误消息:
sign.hs:9:26:
Illegal instance declaration for ‘Signed 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 ‘Signed a’
Failed, modules loaded: none.
正如编译器指出的那样,您需要打开 FlexibleInstances
以及 UndecidableInstances
.GHC 的错误消息通常非常具体,尤其是当您忘记打开语言扩展时。以下立即编译:
{-# LANGUAGE UndecidableInstances, FlexibleInstances #-}
data Sign = Negative | Zero | Positive
deriving (Eq, Ord, Read, Show)
class Signed a where
sign :: a -> Sign
instance (Integral a) => Signed a where
sign = undefined
但是,我认为Signed
类在这个例子中可能是一个错误。定义一个(非重载的(顶级函数要简单得多,不需要UndecidableInstances
(对的需求通常是一种设计气味(,并且更能表达代码的含义:"你可以得到符号的东西"正是实数。
sign :: Real a => a -> Sign
sign x
| x == 0 = Zero
| x < 0 = Negative
| otherwise = Positive