我有以下类型类实例:
type Scalar = Double
data Vector = Vector [Double] deriving (Show, Eq)
instance Num Vector where
(+) (Vector xs) (Vector ys) = Vector (zipWith (+) xs ys)
(-) (Vector xs) (Vector ys) = Vector (zipWith (-) xs ys)
(*) (Vector xs) (Vector ys) = Vector (zipWith (*) xs ys)
instance Fractional Vector where
(/) (Vector xs) (Vector ys) = Vector (zipWith (/) xs ys)
dot :: Vector -> Vector -> Vector
dot (Vector v1) (Vector v2) = sum $ v1 + v2
然而 dot 方法不进行类型检查。我猜它不能使用 + 方法,即使它在 Vector 类上。
No instance for (Num [Double])
arising from a use of `+'
Possible fix: add an instance declaration for (Num [Double])
In the second argument of `($)', namely `v1 + v2'
In the expression: sum $ v1 + v2
In an equation for `dot':
dot (Vector v1) (Vector v2) = sum $ v1 + v2
编辑:嗯,这很尴尬。