为什么在尝试用ghci加载此Haskell代码时会出现错误?
我在Haskell做一些练习: 我试图将函数“delscnds”重写为一个endrecursive函数“delscndsER”。 你可以在下面看到我的试穿为什么在尝试用ghci加载此Haskell代码时会出现错误?,haskell,Haskell,我在Haskell做一些练习: 我试图将函数“delscnds”重写为一个endrecursive函数“delscndsER”。 你可以在下面看到我的试穿 delscnds, delscndsER :: [t0] -> [t0] delscnds [] = [] delscnds [x] = [x] delscnds (x:y:xs) = x : delscnds xs delscndsER (x:y:xs) = delscndsER' (x:y:xs) []
delscnds, delscndsER :: [t0] -> [t0]
delscnds [] = []
delscnds [x] = [x]
delscnds (x:y:xs) = x : delscnds xs
delscndsER (x:y:xs) = delscndsER' (x:y:xs) []
where
delscndsER' (x:y:xs) akk | xs == [x] = (akk ++ x)
| otherwise = delscndsER' xs (akk ++ x)
正常的“delscnds”工作正常,但当我尝试用ghci加载“delscndsER”时,它提示我终端中出现错误,我没有真正得到问题。
你能告诉我ghci到底在抱怨什么吗?
我也可以让这个想法发挥作用,还是我需要一种不同的方法?
任何提示都将不胜感激
以下是ghci错误:
• Occurs check: cannot construct the infinite type: t0 ~ [t0]
Expected type: [[t0]]
Actual type: [t0]
• In the first argument of ‘delscndsER'’, namely ‘(x : y : xs)’
In the expression: delscndsER' (x : y : xs) []
In an equation for ‘delscndsER’:
delscndsER (x : y : xs)
= delscndsER' (x : y : xs) []
where
delscndsER' (x : y : xs) akk
| xs == [x] = (akk ++ x)
| otherwise = delscndsER' xs (akk ++ x)
• Relevant bindings include
xs :: [t0] (bound at Übungsaufgaben5.hs:31:17)
y :: t0 (bound at Übungsaufgaben5.hs:31:15)
x :: t0 (bound at Übungsaufgaben5.hs:31:13)
delscndsER :: [t0] -> [t0] (bound at Übungsaufgaben5.hs:31:1)
delscndsER (x:y:xs) = delscndsER' (x:y:xs) []
^^^^^^
这应该起作用:
delscndsER (x:y:xs) = delscndsER' (x:y:xs) []
where
delscndsER' [] akk = akk
delscndsER' [x] akk = akk ++ [x]
delscndsER' (x:y:xs) akk = delscndsER' xs (akk ++ [x])
正如威廉指出的那样,xs==[x]
不是检查列表是否包含单个元素的正确方法。这也省去了xs=[]
的情况
最后,concat的类型签名是
(++)::[a]->[a]->[a]
,这意味着akk++x
应该是akk++[x]
您想用xs==[x]
检查什么?还不完全清楚您试图完成什么。函数的漏洞在于删除给定列表中的每一个第二个元素。(我想我忘记了,对不起)我的想法是检查一下,如果列表尾xs只包含一个元素,那么就没有第二个元素可以删除了,函数终止了。感谢您的详细解释和指出类型签名,作为一个初学者,这对我理解问题的确切位置有很大帮助。也谢谢威廉指出,这句话有问题。@bamm没问题!如果您还没有意识到,您可以随时在检查函数及其类型。啊,感谢您的提示,我只知道您可以通过命令:t在ghci中获取funktiontypes。