我有一个包含元组元素的列表,例如:
[(1,2),(3,9),(7,9),(6,4),(1,2),(4,2),(3,9),(1,2)]
我需要将第一个元素与其余元素进行比较,然后将第二个项目与列表的其余部分进行比较,以此类推,以返回重复的元素
在这种情况下,它应该返回
(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)
结束条件不正确,总是返回列表的最后一个元素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