模糊的类型变量,但不在ghci中? [英] Ambiguous type variable but not in ghci?
问题描述
任何人都可以解释为什么haskell在下面的例子中强制显式类型签名,以及如何修改它以避免需要显式声明?
将限定的Data.List导入为L
main = do
print $ length $ L.nub [1,1,2,3] - 3,通过(方程a,数字a)=> [a]
print $ length $ L.nub [] - 模糊类型错误,已通过(Eq a)=> [a]
- 可以帮助键入带有明确签名的系统,但如何避免?
print $ length $ L.nub([] :: [Int])
令人惊讶的是在ghci中交互式编写的相同代码没有歧义,并且打印零长度:
λ> :m + Data.List
λ>打印$ length $ nub []
0 - ??你可以解释吗 ??
更新:
看起来与< c $ c> Data.List.nub 长度函数不会停止对不明确类型的投诉:
length':: Eq a => [a] - > Int
length'[] = 0
length'(x:xs)= 1 + length'xs
main = do
print $ length'$ nub [ ]
- 没有使用'length'引起的(Eq a0)实例
- 类型变量'a0'不明确
问题是 []
具有多态类型(等式a)=> [α]
。由于长度
不会添加任何特定约束。 $ b
特别是长度
是:
长度:: [a] - > Int
这比 nub
:
nub :: Eq a => [a] - > [a]
编译器需要使用长度
那里,并且不能推断出
a
的类型。
现在你有两个选项:
- 使用
来打开
ExtendedDefaultRules
#LANGUAGE ExtendedDefaultRules# - } - 显式:
... L.nub([]: :[Int])
默认情况下,我会推荐第二个,除非您完全理解第一个的后果。
Can anybody explain why haskell enforces explicit type signature in the following example and how to modify it to avoid need of the explicit declaration ?
import qualified Data.List as L
main = do
print $ length $ L.nub [1,1,2,3] -- 3, passed (Eq a, Num a) => [a]
print $ length $ L.nub [] -- ambiguous type error, passed (Eq a) => [a]
-- can help type system with explicit signature but how to avoid ?
print $ length $ L.nub ([] :: [Int])
Surprisingly the same code written interactively in ghci has no issue with ambiguity and does prints zero length:
λ> :m +Data.List
λ> print $ length $ nub []
0 -- ?? can you explain ??
Update:
It seems even same restricted as Data.List.nub
length function won't stop complaints about ambiguous type:
length' :: Eq a => [a] -> Int
length' [] = 0
length' (x:xs) = 1 + length' xs
main = do
print $ length' $ nub []
-- No instance for (Eq a0) arising from a use of ‘length'’
-- The type variable ‘a0’ is ambiguous
The problem is that []
has the polymorphic type (Eq a) => [a]
. Since length
doesn't add any particular constraint.
Specifically the type of length
is:
length :: [a] -> Int
which is even more permissive than nub
:
nub :: Eq a => [a] -> [a]
The compiler needs to use a specific instance of length
there and is not able to deduce a type for a
.
Now you have two options:
- Turn on the
ExtendedDefaultRules
extension with{-# LANGUAGE ExtendedDefaultRules #-}
at the beginning of the file. - Be explicit:
... L.nub ([] :: [Int])
I'd recommend the 2nd one by default, unless you fully understand the consequences of the first one.
这篇关于模糊的类型变量,但不在ghci中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!