我有一個「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