Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find duplicates in a list of tuples?

Tags:

haskell

tuples

What would be the best way to filter through a list of tuples and return only the ones where the fst and snd value are the same ?

[(2,1),(2,2),(3,1),(10,9),(10,10)] 

would return (2,2) and (10,10).

like image 230
user4357505 Avatar asked Dec 18 '14 21:12

user4357505


2 Answers

The easiest way is to just use filter with a lambda: filter (\ (a, b) -> a == b) ls.

You could also be cute and use uncurry, which changes a normal function of two arguments into one that takes a tuple, giving you filter (uncurry (==)). Remember that (==) is just a function of type Eq a => a -> a -> Bool, so uncurry (==) is a function of type Eq a => (a, a) -> Bool, which is exactly what you're looking for.

like image 78
Tikhon Jelvis Avatar answered Sep 23 '22 10:09

Tikhon Jelvis


You can do it using list comprehensions:

doubles ls = [(x,y) | (x,y) <- ls, x==y]
like image 28
Eugene Sh. Avatar answered Sep 22 '22 10:09

Eugene Sh.