美好的一天。我是Haskell的新手。關於聲明和實例化一些自定義類,有一點我不清楚。Haskell:具有類類型參數的類實例
haskell中有一個標準類
Integral
。根據hackage,Integral
聲明強制方法quot :: a -> a -> a
。所以這意味着該類的每個實例都應該有這個方法的實現,對吧?我們可以聲明一些功能,採用積分作爲參數,如:
proba :: (Integral a) => a -> a -> a
proba x y = x `quot` y
到目前爲止好
- 現在讓我們宣佈我們的自己的類普羅巴:
class Proba a where
proba :: a -> a -> a
我可以實現像這樣的Int或Integer(或其他數據類型)實例:
instance Proba Integer where
proba x y = x `quot` y
instance Proba Int where
proba x y = x `quot` y
但我不想。 我想爲每個Integral提供一個實例。但是當我嘗試這樣做,我得到一個錯誤:
instance (Integral a) => Proba a where
proba x y = x `quot` y
Illegal instance declaration for `Proba a'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use FlexibleInstances if you want to disable this.)
In the instance declaration for `Proba a'
好吧,它似乎問我要不同類型變量而不是類。但爲什麼?!爲什麼僅僅在這裏有Integral
這不夠?由於quot
是每Integral
申報的,所以這個實例應該對每個Integral
都有效,不是嗎?
也許有辦法達到同樣的效果嗎?
'如果您想禁用此功能,請使用FlexibleInstances。「您是否試過這樣做? – 2014-09-10 15:03:22
我肯定會這樣做,但我想知道爲什麼這些東西隱藏在某個自定義選項的後面,並且默認情況下不可用? – skapral 2014-09-10 15:06:41
因爲原因;這在技術上是默認情況下語言如何工作的擴展。你可以閱讀所有[這裏](https://www.haskell.org/ghc/docs/7.4.2/html/users_guide/ghc-language-features.html)。 – 2014-09-10 15:08:05