新手问题。让我们说我已经创建了一个简单的列表类型类,它带有两个字符串,如果它们是整数,则添加它们各自的元素,如果它们是字符串,则将它们连接起来:
class NewList a where
addLists :: [a] -> [a] -> [a]
instance NewList Int where
addLists = addNumLists
addNumLists :: [Int] -> [Int] -> [Int]
addNumLists (x : xs) (y : ys) = x + y : addNumLists xs ys
addNumLists _ _ = []
instance NewList Char where
addLists x y = concat [x,y]
这会编译,但如果我在GHCi中运行addLists [1,2,3] [1,2,3]
,我会收到错误
<interactive>:278:11:
Ambiguous type variable `a0' in the constraints:
(Num a0) arising from the literal `1' at <interactive>:278:11
(NewList a0)
arising from a use of `addLists' at <interactive>:278:1-8
Probable fix: add a type signature that fixes these type variable(s)
In the expression: 1
In the first argument of `addLists', namely `[1, 2, 3]'
In the expression: addLists [1, 2, 3] [1, 2, 3]
在表达式中添加:: [Int]
可以对其进行评估,但我不了解错误出现的原因。
答案 0 :(得分:7)
因为integral literal numbers的默认设置是Integer
,而不是Int
:
4.3.4模糊类型和重载数值运算的默认值
[...]
每个模块只允许一个默认声明,其效果仅限于该模块。如果模块中没有给出默认声明,那么它假定为:
default (Integer, Double)
请注意,如果您更改addNumLists
的类型并添加Integer
实例,则可以轻松解决此问题:
-- We don't need `Int`, we only need `+`, so anything that is `Num` should work
addNumLists :: (Num a) => [a] -> [a] -> [a]
addNumLists (x : xs) (y : ys) = x + y : addNumLists xs ys
addNumLists _ _ = []
instance NewList Integer where
addLists = addNumLists