我有一个“Shape”类,它应该在所有实例上定义“area”。区域返回包含数字(b属于Num类型类型)的“区域b”(数据类型),表示该形状的区域。类型类实例中的错误绑定类型变量
Haskell有问题将b绑定到(x * y),其中x和y的类型是'a','a'也是类型类型Num。 我该如何解决这个问题? [如果我通过0代替(X * Y),它的工作原理,但不与(0 ::智力)甚至工作]
代码:
data Unit = Unit | Meter | CentiMeter deriving Show
data Area a = Area a Unit deriving Show
class Shape a where
area :: (Num b) => a -> Area b
data Rectangle side = Rectangle side side Unit deriving Show
instance (Num a) => Shape (Rectangle a) where
area (Rectangle x y unit) = Area (x*y) unit
错误:
[1 of 1] Compiling Main (y.hs, interpreted)
y.hs:11:46:
Could not deduce (a ~ b)
from the context (Num a)
bound by the instance declaration at y.hs:10:10-39
or from (Num b)
bound by the type signature for
area :: Num b => Rectangle a -> Area b
at y.hs:11:10-52
`a' is a rigid type variable bound by
the instance declaration at y.hs:10:15
`b' is a rigid type variable bound by
the type signature for area :: Num b => Rectangle a -> Area b
at y.hs:11:10
In the second argument of `(*)', namely `y'
In the first argument of `Area', namely `(x * y)'
In the expression: Area (x * y) unit
Failed, modules loaded: none.
必须阅读关于类型族,因为我在类似的方向思考。 – Karan 2012-02-29 15:42:37
但你的第二个解决方案太好了,适合我目前的需求。 – Karan 2012-02-29 15:44:38
@Karan:太棒了!如果我的回答对您有帮助,您应该点击旁边的复选标记将其标记为已接受:) – ehird 2012-02-29 15:48:05