2017-08-08 29 views
-2

我有以下代碼:沒有實例(民A0)從使用的「它」產生

{-# LANGUAGE OverloadedStrings, FlexibleInstances #-} 

type VersionCompound = Maybe Int 

class VersionOperations a where 
    decrement :: a -> a 

instance VersionOperations VersionCompound where 
     decrement Nothing = Nothing 
     decrement (Just 0) = Just 0 
     decrement (Just num) = Just (num - 1) 

當我嘗試運行命令decrement (Just 5),我得到以下錯誤:

<interactive>:8:1: 
    No instance for (Num a0) arising from a use of ‘it’ 
    The type variable ‘a0’ is ambiguous 
    Note: there are several potential instances: 
     instance Num Data.Attoparsec.Internal.Types.Pos 
     -- Defined in ‘Data.Attoparsec.Internal.Types’ 
     instance Integral a => Num (GHC.Real.Ratio a) 
     -- Defined in ‘GHC.Real’ 
     instance Num Integer -- Defined in ‘GHC.Num’ 
     ...plus five others 
    In the first argument of ‘print’, namely ‘it’ 
    In a stmt of an interactive GHCi command: print it 

任何想法如何解決它?

+7

'遞減(只是5):: VersionCompound'應該給它它需要編譯的信息。儘管如此,你應該真的使用'newtype'。 – 4castle

+1

'遞減(Just(5 :: Int))'是使其編譯的另一種方法 – Jogger

回答

3

Ghc說它不能推斷使用什麼類型。如果運行:t decrement (Just 5),則會看到它的類型爲(Num a, VersionOperations (Maybe a)) => Maybe a

我們可以看到,目前只有一個「a」值滿足這個要求,但是ghc不能。事實上,如果有人在程序的其他地方添加一個例如instance VersionOperations (Maybe Float) where的實例,它將變得非常模糊。

最簡單的解決方案是隻添加一個明確的類型簽名。 decrement (Just 5) :: Maybe Int應該可以工作。

相關問題