为什么这个Haskell代码产生“无限类型”错误?

时间:2009-04-27 21:16:39

标签: haskell types type-inference

我是Haskell的新手,面对一个“无法构造无限类型”的错误,我无法理解。

事实上,除此之外,我还没有找到这个错误甚至意味着什么的好解释,所以如果你能超越我的基本问题并解释“无限类型”错误,我真的很感激它

以下是代码:

intersperse :: a -> [[a]] -> [a]

-- intersperse '*' ["foo","bar","baz","quux"] 
--  should produce the following:
--  "foo*bar*baz*quux"

-- intersperse -99 [ [1,2,3],[4,5,6],[7,8,9]]
--  should produce the following:
--  [1,2,3,-99,4,5,6,-99,7,8,9]

intersperse _ [] = []
intersperse _ [x] = x
intersperse s (x:y:xs) = x:s:y:intersperse s xs

这是尝试将其加载到解释器中的错误:

Prelude> :load ./chapter.3.ending.real.world.haskell.exercises.hs
[1 of 1] Compiling Main (chapter.3.ending.real.world.haskell.exercises.hs, interpreted )

chapter.3.ending.real.world.haskell.exercises.hs:147:0:
Occurs check: cannot construct the infinite type: a = [a]
When generalising the type(s) for `intersperse'
Failed, modules loaded: none.

感谢。

-

这里有一些更正了代码和处理Haskell中“无限类型”错误的一般准则:

更正后的代码

intersperse _ [] = []
intersperse _ [x] = x
intersperse s (x:xs) =  x ++ s:intersperse s xs 

问题是什么:

我的类型签名表明散布的第二个参数是列表列表。因此,当我模式匹配“s(x:y:xs)”时,x和y变为列表。然而,我将x和y视为元素,而不是列表。

处理“无限类型”错误的指南:

大多数情况下,当你收到这个错误时,你已经忘记了你正在处理的各种变量的类型,并且你试图使用一个变量,好像它是一些其他类型的变量而不是它是。仔细查看所有类型与您使用它的方式类型,这通常可以发现问题。

4 个答案:

答案 0 :(得分:30)

问题出在最后一个子句中,将x和y视为元素,而它们是列表。这将有效:

intersperse _ [] = []
intersperse _ [x] = x 
intersperse s (x:y:xs) = x ++ [s] ++ y ++ intersperse s xs

发生无限类型错误,因为:运算符具有类型a - > [a] - > [a],而你将其视为[a] - > a - > [a],这意味着[a]必须用a来标识,这意味着a是一个无限嵌套的列表。这是不允许的(而不是你的意思,无论如何)。

编辑:上述代码中还有另一个错误。它应该是:

intersperse _ [] = []
intersperse _ [x] = x
intersperse s (x:xs) = x ++ [s] ++ intersperse s xs

答案 1 :(得分:4)

通常添加显式类型定义可以使编译器的类型错误消息更有意义。但在这种情况下,显式输入会使编译器的错误消息更糟。

当我让ghc猜出散布的类型时,看看会发生什么:

Occurs check: cannot construct the infinite type: a = [a]
  Expected type: [a] -> [[a]] -> [[a]]
  Inferred type: [a] -> [[a]] -> [a]
In the second argument of `(:)', namely `intersperse s xs'
In the second argument of `(:)', namely `y : intersperse s xs'

这清楚地指出了代码中的错误。使用这种技术,您不必像其他人所建议的那样盯着所有事物并仔细思考类型。

答案 2 :(得分:3)

我可能错了,但似乎你正试图解决一个更难的问题。你的intersperse版本不只是将值与数组散布在一起,而且还将它展平一层。

Haskell中的List模块实际上提供了一个散布函数。它输入列表中每个元素之间给出的值。例如:

intersperse 11 [1, 3, 5, 7, 9] = [1, 11, 3, 11, 5, 11, 7, 11, 9]
intersperse "*" ["foo","bar","baz","quux"] = ["foo", "*", "bar", "*", "baz", "*", "quux"]

我认为这是你想要做的,因为这是我教授在学习Haskell时希望我们做的事情。当然,我可以完全退出。

答案 3 :(得分:0)

我还发现this解释了错误的含义。

每次解释器/编译器都给我这个错误时,因为我使用了一些类型参数化的元组作为形式参数。通过删除函数的类型定义,包含类型变量,一切正常。

我仍然无法弄清楚如何修复它并保留函数类型定义。

相关问题