简体   繁体   English

Haskell:筛选带条件的元组列表

[英]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. Il看起来很简单,但我对此深信不疑。 The list of tuples is all ready generated 元组列表已准备就绪

eg : [(10,11),(11,10),(11,12),(12,11),(13,15),(13,14)] 例如: [(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 我想返回一个相同元组的列表,但是当一个元组(x1,y1)和(x2,y2)其中x1 == y2和y1 = x2并属于该列表时,仅返回(x1,y1)一个

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. 这将在测试用例中返回[[13,14),(13,15),(11,12),(10,11)],以防顺序很重要,您可以将其反转。

This solution is without using any libraries, else you can use a nubBy like another person said. 此解决方案无需使用任何库,否则您可以像其他人所说的那样使用nubBy。

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: 我已经看到它已经得到了回答,但是由于haskell非常有趣,并且总是有更多可能的解决方案,因此我将添加一个发现的解决方案:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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