簡體   English   中英

在 Haskell 中將 Int 定義為 class 類型的實例時出現問題

[英]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 +++ 23並且我沒有收到錯誤。

問題:當使用Int作為實例時,為什么它不起作用? 使用IntInteger什么區別?

鑒於它適用於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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM