Haskell函数组成 - 错误推断类型

时间:2013-05-15 17:12:39

标签: haskell functional-programming dot-operator

在下面的Haskell代码中,函数typeError没有进行类型检查。

wrap x = [x]

listf :: [[a]] -> [[a]]
listf = id

typeCheck :: [a] -> [[a]]
typeCheck x = listf (wrap x)

typeError :: [a] -> [[a]]
typeError = wrap . listf

GHC如果取消注释会产生此错误:

Couldn't match type `a' with `[a0]'
  `a' is a rigid type variable bound by
      the type signature for typeError :: [a] -> [[a]] at tim.hs:10:1
Expected type: [a] -> [a]
  Actual type: [[a0]] -> [[a0]]
In the second argument of `(.)', namely `listf'
In the expression: wrap . listf

我不明白为什么。 a应该能够与[a0]统一 - 它们是独立的类型变量。这正是它为typeCheck推断的类型 - 但不是在使用.运算符时。

Hugs会产生一个非常相似且同样虚假的错误消息:

ERROR "repro.hs":10 - Inferred type is not general enough
*** Expression    : typeError
*** Expected type : [a] -> [[a]]
*** Inferred type : [[a]] -> [[[a]]]

此外,这很好用:

listf' :: [a] -> [a]
listf' = id

typeCheck' :: [a] -> [[a]]
typeCheck' = wrap . listf'

问题仅发生在[[a]]或[[[a]]]或更高的情况下。这是什么交易?

1 个答案:

答案 0 :(得分:5)

你似乎已经扭转了这里的功能构成。

-- This
typeCheck :: [a] -> [[a]]
typeCheck x = listf (wrap x)

-- is the same as
typeCheck' :: [a] -> [[a]]
typeCheck' = listf . wrap

-- while this
typeError :: [a] -> [[a]]
typeError = wrap . listf

-- is the same as
typeError' :: [a] -> [[a]] 
typeError' x = wrap (listf x)

现在应该明白为什么这不起作用。 listf要求其参数为[[a]],但typeError的签名声称它适用于任何[a]

相关问题