简体   繁体   中英

Haskell: Filter a list of tuples with condition

I have a list of tuples on which I want to apply certain condition. Il looks simple but I'm stuck with this. The list of tuples is all ready generated

eg : [(10,11),(11,10),(11,12),(12,11),(13,15),(13,14)]

I want to return a list of the same tuples but when a tuple (x1,y1) and (x2,y2) where x1 == y2 and y1 = x2 and belongs to the list only the (x1,y1) one is returned

My function header

myFun :: Ord a => [(a,a)] -> [(a,a)]
    myFun = ....

And the expected result should be like this(from the same list)

[(10,11),(11,12),(13,15),(13,14)]

Any indications, ideas or hints are welcomed.

After some trying I came up with this:

myFun::Ord a => [(a,a)] -> [(a,a)]
myFun ls = auxfun [] ls

auxfun:: Eq a => [(a,a)] -> [(a,a)] -> [(a,a)]
auxfun [] [] = []
auxfun [] (l:ls) = auxfun [l] ls
auxfun ls [] = ls
auxfun ls1 ((x,y):ls2)
    |(y,x) `elem` ls1 = auxfun ls1 ls2
    |otherwise = auxfun ((x,y):ls1) ls2

This will return you [(13,14),(13,15),(11,12),(10,11)] in your test case, in case the order matters you can just reverse it.

This solution is without using any libraries, else you can use a nubBy like another person said.

I see it has been answered already, but since haskell is so much fun and there are always more possible solutions I'll add one that I found:

foldr (\x y -> if x == rev (head) y then (x:tail y) else x:y) [rev $ last xs] xs where
  rev (a,b) = (b,a)

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