【发布时间】:2012-02-29 15:13:04
【问题描述】:
我有一个“形状”类,它应该在所有实例上定义“区域”。 area 返回“Area b”(一种数据类型),其中包含一个数字(b 属于 Num 类型类),表示该 Shape 的面积。
Haskell 将 b 绑定到 (x*y) 时遇到问题,其中 x 和 y 的类型为“a”,而“a”也属于类型类 Num。 我该如何解决这个问题? [如果我将 (x*y) 替换为 0,它可以工作,但即使使用 (0::Int) 也不能工作]
代码:
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.
【问题讨论】:
标签: haskell instance typeclass