你好,我需要創建一個類,其中包含一個方法prize'
計算一些分數。我想實例的情況下,我得到一個Order
,以後我將不得不再比如如果我得到一個[Order]
,這是代碼:Haskell類的誤解
class Ped a where
prize' :: Fractional b => a -> b
instance (Integral n, Fractional p) => Ped (Order n p) where
prize' x = prizeOrder x
data (Integral c,Fractional p) => Product c p
= Prod c String p
deriving (Show, Read)
data (Integral n, Fractional p) => Order n p
= PdMult (Product n p) n
| PdUnit (Product n p)
deriving (Show, Eq)
prize :: (Fractional p, Integral c) =>(Product c p) -> p
prize (Prod _ _ x) = x
prizeOrder :: (Fractional p, Integral c) => (Order c p) -> p
prizeOrder (PdMult p n) = (prize p) * (fromIntegral n)
prizeOrder (PdUnit p) = prize p
前奏說:
Could not deduce (p ~ b)
from the context (Integral n, Fractional p)
bound by the instance declaration
at src\Funciones.hs:6:10-55
or from (Fractional b)
bound by the type signature for
prize' :: Fractional b => Order n p -> b
at src\Funciones.hs:7:5-11
`p' is a rigid type variable bound by
the instance declaration
at src\Funciones.hs:6:10
`b' is a rigid type variable bound by
the type signature for prize' :: Fractional b => Order n p -> b
at src\Funciones.hs:7:5
Expected type: Order b
Actual type: Order n p
Relevant bindings include
x :: Order n p
(bound at src\Funciones.hs:7:13)
prize' :: Order n p -> b
(bound at src\Funciones.hs:7:5)
In the first argument of `prizeOrder', namely `x'
In the expression: prizeOrder x
首先,不要將類限制放在數據類型上。如果您需要GADT的功能,但看起來這不是您需要的解決方案。 – bheklilr
問題是你的班級說:我可以把它轉換成你想要的任何'分數',而數據明確地根據你所做的決定來限制它。 –
我已經完成了一個使用它們的大程序,它能正常工作,但它第一次在程序中創建一個類:) – KannaKiski