我正在尝试定义一个类型类Plotable,它提供了一个函数plotable来返回表示图表(x,y)中坐标的元组,如果x和y的类型不一定是特定的(即Double),我认为它们可以是任何number类型(它们被移交给Chart)。
我希望plotable能够处理Num a => Complex a和Num a => (a, a),所以我写道:
class Plotable a where
plotable :: Num b => a -> (b, b)
instance Num a => Plotable (a, a) where
plotable = id
instance Num a => Plotable (Complex a) where
plotable c = (realPart c, imagPart c)这对我来说是有意义的,但是我得到了错误:
Couldn't match type ‘a’ with ‘b’
‘a’ is a rigid type variable bound by
the instance declaration
at /Users/dan.brooks/Code/haskell/coding-the-matrix/src/TheField/Plot.hs:12:10-33
‘b’ is a rigid type variable bound by
the type signature for:
plotable :: forall b. Num b => (a, a) -> (b, b)
at /Users/dan.brooks/Code/haskell/coding-the-matrix/src/TheField/Plot.hs:13:3-10
Expected type: (a, a) -> (b, b)
Actual type: (b, b) -> (b, b)但是,如果a被约束为Num,而b被约束为Num,那么传递相同的值在这种情况下应该可以吗?这仅仅是compilier的一个限制吗?或者我误用了类型类和类型约束?
发布于 2018-01-05 21:16:10
plotable :: Num b => a -> (b, b)意味着其中的任何一个都必须键入check
plotable :: a -> (Int, Int)
plotable :: a -> (Integer, Integer)
plotable :: a -> (Double, Double)
...换句话说,多态类型向用户承诺,plotable可以使用用户可以选择任何数值类型的b。
id :: a -> a不允许用户选择b,所以它不够通用。
https://stackoverflow.com/questions/48114347
复制相似问题