Haskell 类实例中的不明确变量
新手问题。假设我创建了一个简单的list typeclass,它接受两个字符串,如果它们是整数,则添加它们各自的元素;如果它们是字符串,则将它们连接起来:Haskell 类实例中的不明确变量,haskell,typeclass,Haskell,Typeclass,新手问题。假设我创建了一个简单的list typeclass,它接受两个字符串,如果它们是整数,则添加它们各自的元素;如果它们是字符串,则将它们连接起来: class NewList a where addLists :: [a] -> [a] -> [a] instance NewList Int where addLists = addNumLists addNumLists :: [Int] -> [Int] -> [Int] addNumLi
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中运行addlist[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]
:278:11:
约束中不明确的类型变量“a0”:
(Num a0)源于278:11处的文字“1”
(新列表a0)
因使用地址:278:1-8的“地址列表”而产生
可能修复:添加修复这些类型变量的类型签名
在表达式中:1
在“addLists”的第一个参数中,即“[1,2,3]”
在表达式中:addlist[1,2,3][1,2,3]
将::[Int]
添加到表达式中可以对其求值,但我不明白为什么首先会出现错误。因为的默认值是整数,而不是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