a
在你的(a,a)
实例中将是一个任意的Num
实例.该a
在vmult :: Num a => v -> a -> v
什么都不知道这一点,即这可能是任何其他 Num
实例.
要使课程成功,你需要
确保数字类型可以相互转换.例如,
class Vector v where vplus :: v -> v -> v vmult :: RealFrac a => v -> a -> v instance RealFrac a => Vector (a, a) where (a, b) `vplus` (c, d) = (a + c, b + d) (a, b) `vmult` m' = (a * m, b * m) where m = realToFrac m'
确保标量乘数实际上与向量分量的类型相同.这就是矢量空间库的作用.对于您的代码,它将采用表单
{-# LANGUAGE TypeFamilies, FlexibleInstances #-} class Vector v where type Scalar v :: * vplus :: v -> v -> v vmult :: v -> Scalar v -> v instance Num a => Vector (a, a) where type Scalar (a,a) = a (a, b) `vplus` (c, d) = (a + c, b + d) (a, b) `vmult` m = (a * m, b * m)