如何在此处解决“ ***例外:Prelude.head:空列表”

Mor*_*ang 2 haskell

这是一项作业,它是删除相邻的重复项。结果应该像这样removeAdjacentDuplicates [3,1,2,2,2,2,2,4,4,2,2,3] == [3,1,2,4,2,3]

我知道没有必要在head这里使用,但是不允许使用rekursion和格式为[e | ...]。仅Prelude中的功能是允许的,group依此类推,在其他软件包中也不允许。map zip filter concat reverse foldr推荐。

例如,不可能做到这一点:

removeAdjacentDuplicates :: Eq a => [a] -> [a]
removeAdjacentDuplicates (x:xs@(y:_))
 | x == y    = x:tail (removeAdjacentDuplicates xs)
 | otherwise = x:removeAdjacentDuplicates xs
Run Code Online (Sandbox Code Playgroud)

所以我尝试这样

removeAdjacentDuplicates = foldr (\x result -> if ( x == (head result)) then result else (x : result)) []

Run Code Online (Sandbox Code Playgroud)

但是当我测试它时,它就扔掉*** Exception: Prelude.head: empty list' here

我曾经尝试添加removeAdjacentDuplicates [] = []
但是错误是这样的

Equations for ‘removeAdjacentDuplicates’ have different numbers of arguments
      H7-1.hs:24:1-32
      H7-1.hs:25:1-105
   |
24 | removeAdjacentDuplicates [] = []
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
Run Code Online (Sandbox Code Playgroud)

我不知道问题出在哪里,如何解决?

Dan*_*ner 6

x == head result死于if result[]-并且result肯定[]在的第一次迭代中foldr,因此在输入列表不需要foldr进行任何迭代时添加一个特殊情况正好解决了错误的情况!

result您可以尝试将其插入列表中,而不是尝试从列表中提取值x。所以考虑使用条件

[x] == take 1 result
Run Code Online (Sandbox Code Playgroud)

相反-它永远不会消失。