2

我正在尝试编写一个具有任意数量参数的函数。这些参数可以是 Int 或 String。我对整数有疑问。出于某种原因(我不明白),值 1 成为歧义的来源。如何处理这个错误,它的根源是什么?

{-# LANGUAGE FlexibleInstances #-}
import Data.Typeable

data PackArgTypes = PackInt Int | PackString String
                              deriving Show

class PackArg t where
  toPackArg :: t -> PackArgTypes

instance PackArg Int where
  toPackArg = PackInt . fromIntegral
instance PackArg Integer where
  toPackArg = PackInt . fromIntegral

instance PackArg String where
  toPackArg = PackString

class PackType t where
  pack' :: String -> [PackArgTypes] -> t

instance PackType (IO a) where
  pack' fmt acc = do
    print fmt
    mapM_ print acc
    return undefined

instance (PackArg a, PackType r) => PackType (a -> r) where
    pack' fmt acc = \x -> pack' fmt $ acc ++ [toPackArg x]

pack :: (PackType t) => String -> t
pack fmt = pack' fmt []

main :: IO ()
main = do
  pack "asd" "qwe" "asd"(1 :: Int) -- Ok
  pack "asd" "qwe" "asd" 1         -- Sad

在上述情况下,我遇到了错误

test1.hs:33:3-6: No instance for (PackArg a0) arising from a use of ‘pack’ …
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
  instance PackArg String
    -- Defined at /home/knesterov/test1.hs:13:10
  instance PackArg Int -- Defined at /home/knesterov/test1.hs:10:10
In a stmt of a 'do' block: pack "asd" "qwe" "asd" 1
In the expression: do { pack "asd" "qwe" "asd" 1 }
In an equation for ‘main’: main = do { pack "asd" "qwe" "asd" 1 }
test1.hs:33:26: No instance for (Num a0) arising from the literal ‘1’ …
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
  instance Num Double -- Defined in ‘GHC.Float’
  instance Num Float -- Defined in ‘GHC.Float’
  instance Integral a => Num (GHC.Real.Ratio a)
    -- Defined in ‘GHC.Real’
  ...plus 7 others
In the fourth argument of ‘pack’, namely ‘1’
In a stmt of a 'do' block: pack "asd" "qwe" "asd" 1
In the expression: do { pack "asd" "qwe" "asd" 1 }
Compilation failed.

编辑

感谢 user5402 指出了 ghci 和 ghc 之间的区别。Ghci默认启用扩展 ExtendedDefaultRules

因此,加上三行,我的示例可以正常工作。

{-# LANGUAGE ExtendedDefaultRules #-}
instance PackArg Integer where
  toPackArg = PackInt . fromIntegral
4

1 回答 1

3

问题在这里:

The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
  instance Num Double -- Defined in ‘GHC.Float’
  instance Num Float -- Defined in ‘GHC.Float’
  ...

回想一下,文字1可以解释为任何Num类型的值,因此 GHC 不知道选择哪一个 - 例如Int, Double,Rational等。

标准Text.Printf模块也有同样的问题:

import Text.Printf

main = putStrLn $ printf "%d" 3

给他同样的错误。

请注意,如果将此代码输入到 ghci 中不会出现错误,因为存在使表达式成为1单态而不是多态的默认规则。

于 2015-09-04T14:01:11.960 回答