我开始用GHC 7.4.2中的新类约束扩展来弄湿我的脚,但是我有一些问题需要一个小例子来工作。代码如下:haskell约束系列
{-# LANGUAGE UndecidableInstances,
MultiParamTypeClasses,
KindSignatures,
TypeFamilies,
Rank2Types,
ConstraintKinds,
FlexibleInstances,
OverlappingInstances #-}
module Test where
import GHC.Exts -- to get Constraint type constructor
class NextClass f where
type Ctxt f a :: Constraint
next :: (Ctxt f a) => a -> a
instance NextClass Int where
type Ctxt Int a = Num a
next b = b + 1
n :: (NextClass a) => a -> a
n v = next v
我想要做的就是定义一个NextClass
类型的类,这将让我(给定值x)得到X的下一个值是的情况下,所有类型是什么NextClass
。要使用+
运算符,我需要Num a
类约束Int
。
然而,GHC给了我以下错误:
Could not deduce (Ctxt f0 a) arising from a use of `next'
from the context (NextClass a)
bound by the type signature for n :: NextClass a => a -> a
In the expression: next v
In an equation for `n': n v = next v
我怀疑GHC告诉我,它没有足够的信息来确定要使用的约束族实例。
有人可以解释我在做什么错在这里。这是限制家庭的正确使用吗?
TIA
感谢丹尼尔,我改变了我的代码使用'实例Num Int => NextClass Int其中...'。这是在Haskell中编写这种类型代码的惯用方法吗? –
@RananvanDalen那么,惯用的方法是'实例NextClass Int其中...'没有无约束的约束或'newtype SuccNext a = SuccNext a;实例Num a => NextClass(SuccNext a)其中...具有多态类型(以及防止虚假重叠的新类型)。 –
好东西。我必须再读一遍类型类:) –