[英]Problem when defining Int as an instance of a type class in Haskell
我試圖將Int
定義為我的類型 class Add
的實例。 我想定義我自己的運算符+++
,它應該在整數和字符串上重載。 我的目標是能夠使用相同的運算符添加整數和連接字符串。 因此,我使用實例Int
和[char]
創建了類型 class Add
:
class Add a where
(+++) :: a -> a -> a
instance Add Int where
x +++ y = x + y
instance Add [char] where
x +++ y = x ++ y
問題:在計算表達式1 +++ 2
時,GHCi 給我以下錯誤消息:
<interactive>:9:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘print’
prevents the constraint ‘(Show a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Show Ordering -- Defined in ‘GHC.Show’
instance Show Integer -- Defined in ‘GHC.Show’
instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
...plus 22 others
...plus 18 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In a stmt of an interactive GHCi command: print it
但是在將Integer
定義為Add
的實例時
instance Add Integer where
x +++ y = x + y
GHCi 可以評估1 +++ 2
到3
並且我沒有收到錯誤。
問題:當使用Int
作為實例時,為什么它不起作用? 使用Int
或Integer
什么區別?
鑒於它適用於Integer
但不適用於Int
,我很確定這是由於“類型默認”。
在 GHCi 中(在較小程度上在編譯代碼中),如果表達式具有不明確的類型,編譯器會嘗試幾種“默認類型”,其中是Integer
(但不是Int
)。 幾乎可以肯定,這就是差異的來源。
我懷疑如果您將:: Int
添加到表達式的末尾,它將執行得很好。 問題不在於存在類型錯誤,而是可能適合的類型不止一種,並且編譯器不確定您想要的是哪一種。
我從未嘗試過,但我相信您可以通過說default (Int, Double)
之類的話來更改默認值。 (通常是default (Integer, Double)
。)我認為這是正確的語法; 不是100%確定。
GHCi 手冊中有一些關於此的內容: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#type-defaulting-in-ghci
還有 Haskell 報告: https://www.haskell.org/onlinereport/haskell2010/haskellch.404.html (#Section 10-.3.04.5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.