比较列表中的所有元素 haskell

compare all elements in a list haskell

我有一个列表,其中的元素是元组示例:

[(1,2),(3,9),(7,9),(6,4),(1,2),(4,2),(3,9),(1,2)]

我需要将第一个元素与其余元素进行比较,然后将第二个元素与列表的其余部分进行比较,依此类推 return 重复的元素

在这种情况下应该return

(1,2),(1,2),(1,2),(3,9),(3,9)

知道如何实施吗?

我已经实现了这个

test :: Eq a => [(a,a)] -> [(a,a)]
test [(x,y)] = [(x,y)]
test (x:y:xs) 
    |((fst (x) == fst (y)) && (snd (x) == snd (y))) = ( [y]) ++ (test (x:xs) )
    |otherwise = test (x:xs)            

结束条件错误,总是 return 是列表的最后一个元素 test [(x,y)] = [(x,y)]

它只将第一项与列表的其余部分进行比较,但我需要将第二项、第三项...与列表的其余部分进行比较

首先,如果您有两个元组,比较元素与使用 == 相同。所以

-- This code
(fst (x) == fst (y)) && (snd (x) == snd (y))
-- is the same as this code
x == y

其次,注意函数的递归性质。假设您有办法将当前列表拆分为

  • ys 等于第一个元素的列表
  • zs 不等于第一个元素的列表

然后 ys 将是您最终解决方案的第一部分。您需要用 zs 做什么才能得到其余的解决方案?

下面有一条小指南,您可以填写。 (这显然是一个作业,所以我不会给你完整的答案)

-- if you can't use imports, defined yourself this function.
import Data.List (partition)

test :: Eq a => [a] -> [a]
test [] = []
-- Hint: use recursion
test (x:xs) = undefined -- Notice that if ys is empty, then x wouldn't be a repeated element, so it should be discarted. 
 where (ys, zs) = partition (== x) xs
--      |   |- This is the list of element not equals to x
--      |- This is the list of elements equals to x