Reputation: 300
I have two lists of tuples both of the form [(a,b),..].
I wish to compare them and get the common elements - but have tried using intersect, but this does not work. Is there a way of using map/filter to output the intersection as a new list of tuples?
Upvotes: 3
Views: 1415
Reputation: 176
You can use Data.Function.on
function to supply function you need to the first (or second) element of the tuple:
import Data.Function (on)
import Data.List (intersectBy)
intersectBy ((==) `on` fst) [(1,2), (2,3), (3,4)] [(1,2), (2,3), (3,5)]
> [(1,2),(2,3),(3,4)]
Upvotes: 3
Reputation: 42678
Try with a list comprehension:
[x | x <- list1, x `elem` list2]
Example:
Prelude> let list1 = [(1,2), (2,3), (3,4)]
Prelude> let list2 = [(1,2), (2,3), (3,5)]
Prelude> [x | x <- list1, x `elem` list2]
[(1,2),(2,3)]
Anyway, intersect
should work, it works for me:
Prelude> import Data.List
Prelude Data.List> list1 `intersect` list2
[(1,2),(2,3)]
Upvotes: 4