简体   繁体   中英

Intersection of lists of tuples - Haskell

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?

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)]

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM