我是 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
问题是什么:
我的类型签名声明 intersperse 的第二个参数是列表的列表。因此,当我对“s (x:y:xs)”进行模式匹配时,x 和 y 变成了 lists。然而我将 x 和 y 视为元素,而不是列表。
处理“无限类型”错误的指南:
大多数时候,当您遇到此错误时,您已经忘记了您正在处理的各种变量的类型,并且您试图使用一个变量,就好像它是其他类型一样。仔细查看所有内容的类型与您使用它的方式,这通常会发现问题。