rmdup :: [Int] -> [Int]
rmdup [] = []
rmdup (x:xs) | x `elem` xs = rmdup xs
| otherwise = x: rmdup xs
上面的代码从“整数”列表中删除重复项,但删除了第一个匹配项,并保留了第二个匹配项。例如:
rmdup [1,2,3,1,4]
将导致:
[2,3,1,4]
我如何更改它以保持顺序并产生此结果:
[1,2,3,4]
? 注意,我不想使用内置功能。 最佳答案
接下来呢?这避免了疯狂低效的acc ++ [x]
,并且还反转了给定列表两次:
rmdup :: Eq a => [a] => [a]
rmdup xs = rmdup' [] xs
where
rmdup' acc [] = []
rmdup' acc (x:xs)
| x `elem` acc = rmdup' acc xs
| otherwise = x : rmdup' (x:acc) xs