gpt4 book ai didi

haskell - 发生检查: cannot construct the infinite type: t ~ [t]

转载 作者:行者123 更新时间:2023-12-02 14:12:39 25 4
gpt4 key购买 nike

我开始学习 Haskell。我正在尝试运行此代码

-- Helpers.hs
module Helpers
where

lst1 +++ lst2 = if null lst1
then lst2
else (head lst1) : (tail lst1 +++ lst2)


reverse2 lst = if null lst
then []
else reverse2 (tail lst) : (head lst)
-- Main.hs
import Helpers

main :: IO ()
main = putStrLn . reverse2 [2, 8, 7]

我收到此错误:

D:\Haskell\project>cabal configure
Resolving dependencies...
Configuring one-0.1.0.0...

D:\Haskell\project>cabal build
Building one-0.1.0.0...
Preprocessing executable 'one' for one-0.1.0.0...
[1 of 2] Compiling Helpers ( src\Utils\Helpers.hs, dist\build\one\one-t
mp\Helpers.o )

src\Utils\Helpers.hs:11:21:
Occurs check: cannot construct the infinite type: t ~ [t]
Relevant bindings include
lst :: [[t]] (bound at src\Utils\Helpers.hs:9:10)
reverse2 :: [[t]] -> [t] (bound at src\Utils\Helpers.hs:9:1)
In the first argument of `(:)', namely `reverse2 (tail lst)'
In the expression: reverse2 (tail lst) : (head lst)

我该如何解决这个问题?

最佳答案

reverse2 (tail lst) 的类型为 [a],而 head lst 的类型为 a。同时, : 运算符的类型为 a -> [a] -> [a]。当您尝试执行 reverse2 (tail lst) : (head lst) 时,Haskell 认为 head lst 是一个列表,其元素与 reverse2 ( tail lst)——即 head lst::[[a]]。但是,head lst 也必须与 reverse2 (tail lst) 的元素类型相同,这意味着 reverse2 (tail lst)::[[[a ]]],但是 head lst 必须是 [[[[a]]]],然后 reverse2 (tail lst) 必须是 [[[[[a]]]]] 类型,我想你可以看到这是怎么回事。

出现此问题的原因是您错误地使用了 :。如果你想向列表追加一个元素,最简单的方法是reverse2 (tail lst)++ [head lst]

关于haskell - 发生检查: cannot construct the infinite type: t ~ [t],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31171618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com