2011-05-17 45 views
4

我想用適當的轉換類聲明我自己的數據。我的代碼如下所示:Haskell Num類和我的類似節目之間的歧義

data SomeData = SInteger Integer | SElse deriving Show 

class Some a where 
    toSome :: a -> SomeData 

instance Some Int where toSome = SInteger . toInteger 

main :: IO() 
main = print $ toSome 3 

但GHC(7.0.3)變得惱怒地說:

Ambiguous type variable `a0' in the constraints: 
     (Some a0) arising from a use of `toSome' 
       at minimal_broken.hs:11:16-21 
     (Num a0) arising from the literal `3' at minimal_broken.hs:11:23 
    Probable fix: add a type signature that fixes these type variable(s) 

顯式類型簽名(如3 ::智力)修復該問題,但它是非常不方便。
標準的「顯示」工作得很好,根據手冊它的聲明完全一樣。

爲什麼標準顯示作品,但我的班級沒有?我錯過了什麼?

P.S .:明確的「default(Int)」不能解決這個問題。

回答

4

你說得對。這有點棘手。首先,你必須給一個類型簽名解決您的示例數值超載:

Ambiguous type variable `a0' in the constraints: 
    (Some a0) arising from a use of `toSome' at A.hs:11:16-21 
    (Num a0) arising from the literal `3' at A.hs:11:23 

這意味着,當你發現,你必須選擇一個特定的解決方案類型,如int。

那麼Show如何工作?通過延期違約規則的神奇。顯示是特殊的,GHCi啓用一些特殊的違約規則來幫助「默認」type in arguments of Show to Integer

您的新課程並不是擴展默認功能知道的魔法課程之一,因此很遺憾,您需要提供類型註釋。

0

的問題:3類型爲Num a => a,但GHC需要一個具體類型,以搜索的Some實例 (可能的話,有可能存在的Some多個實例是在Num - 所以哪一個選擇?)

1

之所以像擺在首位show 3作品是由於違約規則,挑選一個特定類型時,有涉及Num類的模糊性。它與你的Some類不起作用的原因是規則說所有涉及的類必須是標準類(即從前奏曲等)。這一規則的後半部分有點愚蠢。