关于Haskell中给出的错误的推理编译时的类型错误我发现GHCi 有一个奇怪的行为
test.hs
members :: String -> Bool;
members str = and [ b | x <- str, b <- map (elem x) "abcde" ]
生成以下错误消息
Prelude> :l test.hs
[1 of 1] Compiling Main ( test.hs, interpreted )
test.hs:2:53: error: • Couldn't match type ‘Char’ with ‘t0 Char’ Expected type: [t0 Char] Actual type: [Char] • In the second argument of ‘map’, namely ‘"abcde"’ In the expression: map (elem x) "abcde" In a stmt of a list comprehension: b <- map (elem x) "abcde"
而
GHCi
Prelude> members :: String -> Bool; members xs = and [ b | x <- xs, b <- map (elem x) "abcde"]
产生
<interactive>:18:78: error: • Couldn't match type ‘Char’ with ‘[Char]’ Expected type: [[Char]] Actual type: [Char] • In the second argument of ‘map’, namely ‘"abcde"’ In the expression: map (elem x) "abcde" In a stmt of a list comprehension: b <- map (elem x) "abcde"
更新
我还不明白的是,为什么GHC省略了Foldable t0
类约束-I本以为错误消息是这样的:
test.hs:2:53: error: • Couldn't match type ‘Char’ with ‘t0 Char’ Expected type: Foldable t0 => [t0 Char] Actual type: [Char] • In the second argument of ‘map’, namely ‘"abcde"’ In the expression: map (elem x) "abcde" In a stmt of a list comprehension: b <- map (elem x) "abcde"
由FTP(可折叠遍历建议)函数elem
引入得到了一个新的类型签名。
elem :: (Eq a, Foldable t) => a -> t a -> Bool
GHCi似乎使用了可以被停用的ExtendedDefaultRules
扩展
:set -NoExtendedDefaultRules
这个扩展和trac:10971使得Foldable
和Traversable
默认为[]
。
更新
类约束没有显示,因为它的类型检查是在稍后阶段完成的。