使用'它'时没有(Num a0)的实例

时间:2017-08-08 20:16:54

标签: haskell

我有以下代码:

{-# 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

任何想法如何解决?

1 个答案:

答案 0 :(得分:3)

Ghc说它不能推断出使用什么类型。如果您运行:t decrement (Just 5),则会看到它的类型为(Num a, VersionOperations (Maybe a)) => Maybe a

我们可以看到&#34; a&#34;只有一个值。目前满足这一点,但Ghc不能。实际上,如果有人要在程序中的其他地方添加instance VersionOperations (Maybe Float) where等实例,那么它将变得非常模糊。

最简单的解决方案是只添加一个显式类型签名。 decrement (Just 5) :: Maybe Int应该有用。