我有一个包含元组元素的列表示例:
[(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
关于haskell - 比较列表中的所有元素 haskell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70014230/