我无法弄清楚msg的错误含义。我想在下面定义数据类型的函数距离...我不想使用任何GHC扩展..即使代码很难看,想要在继续使用扩展之前更好地理解错误。有人可以让我知道这个错误意味着什么以及如何摆脱这个错误。
class Vector v where
distance :: v -> v -> Double
-- doesn't make sense, but WTH...
newtype OneD1 a = OD1 a
deriving (Show)
instance Vector (Maybe m) where
distance _ _ = 5.6
instance Vector (OneD1 m) where
distance (OD1 x1) (OD1 x2) = x2-x1
Prelude> :reload
[1 of 1] Compiling Main ( VectorTypeClass.hs, interpreted )
VectorTypeClass.hs:33:33:
Couldn't match expected type `Double' with actual type `m'
`m' is a rigid type variable bound by
the instance declaration
at C:\Users\byamm\Documents\Programming\Haskell\Lab\Expts\VectorTypeClass\VectorTypeClass.hs:32:10
Relevant bindings include
x2 :: m
(bound at C:\Users\byamm\Documents\Programming\Haskell\Lab\Expts\VectorTypeClass\VectorTypeClass.hs:33:27)
x1 :: m
(bound at C:\Users\byamm\Documents\Programming\Haskell\Lab\Expts\VectorTypeClass\VectorTypeClass.hs:33:18)
distance :: OneD1 m -> OneD1 m -> Double
(bound at C:\Users\byamm\Documents\Programming\Haskell\Lab\Expts\VectorTypeClass\VectorTypeClass.hs:33:4)
In the first argument of `(-)', namely `x2'
In the expression: x2 - x1
Failed, modules loaded: none.
Prelude>
答案 0 :(得分:5)
instance Vector (OneD1 m) where
这承诺(OdeD1 m)
是任何m
的向量。包括OneD1 String
等
distance (OD1 x1) (OD1 x2) = x2-x1
我们尝试在-
类型的两个值上应用m
,这可能绝对是任何事情。这里有两个问题:
m
可能不是数字类型 - 目前GHC没有报告此错误。m
类型,但距离应该产生Double
。这是GHC报告的错误。您需要将m
限制为某种数字类型,以便您可以使用-
,并且该类型必须允许转换为Double
,否则您无法满足distance
{1}}签名。
一个简单的方法是:
instance Vector (OneD1 Double) where
distance (OD1 x1) (OD1 x2) = x2-x1
另一个可能是:
instance Real m => Vector (OneD1 m) where
distance (OD1 x1) (OD1 x2) = realToFrac (x2-x1)