[英]Haskell: meaning of the error in GHCI
我无法弄清楚此错误消息的含义。 我想为下面的数据类型定义函数距离...我不想使用任何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>
instance Vector (OneD1 m) where
对于任何m
,这都保证(OdeD1 m)
是一个向量。 包括OneD1 String
等。
distance (OD1 x1) (OD1 x2) = x2-x1
在这里,我们尝试在两个类型为m
值上应用-
绝对可以。 这里有两个问题:
m
可能不是数字类型-GHC目前未报告此错误。 m
,但是距离应该产生Double
。 这是GHC报告的错误。 您需要将m
限制为某种数字类型,以便可以使用-
,并且该类型必须允许转换为Double
,否则您将无法满足distance
签名。
一种简单的方法是:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.