compare all elements in a list haskell

Viewed 278

I have a list with elements that are tuples example:

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

I need to compare the first element with the rest of the elements, then then the second item with the rest of the list and so on to return the repeated elements

In this case it should return

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

any idea how to implement it?

I have this implemented

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)            

the end condition is bad and always returns the last element of the list test [(x,y)] = [(x,y)]

And it only compares the first item with the rest of the list but I need to compare the second, the third ... with the rest of the list

1 Answers

first of all if you have two tuples, comparing element wise is the same as using ==. So

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

Second, notice the recursive nature of your function. Let say you have a way to split your current list into

  • ys the list of elements equal to the first one
  • zs the list of elements not equal to the first one

Then ys will be the first part of your final solution. What do you need to do with zs to get the rest of the solution?

Below, theres is a litle guide line you can fill. (this is obviously an assigment, so I'm not going to give you the full answer)

-- 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
Related