Return unique tuples from a list of tuples in Haskell -
i have list of tuples of form [(a,b),(b,a),(d,c),(e,f),(c,d),(f,e)]
. how return list [(a,b),(c,d),(e,f)]
? solutions i've found remove repeated tuples, , solutions can think of naive o(n^2) solutions. there way efficiently?
if type of components of pairs in class ord
, can in o(n log n) time:
import data.list (sort, group) sortpair :: ord => (a, a) -> (a, a) sortpair (x, y) | x <= y = (x, y) | otherwise = (y, x) uniques :: ord => [(a, a)] -> [(a, a)] uniques = map head . group . sort . map sortpair
so, if define
data t = | b | c | d | e | f deriving (eq, ord, show)
we have, example:
> uniques [(a,b),(b,a),(d,c),(e,f),(c,d),(f,e)] [(a,b),(c,d),(e,f)]
Comments
Post a Comment