简体   繁体   English

过滤Haskell中的元组列表

[英]Filter list of tuples in haskell

I'm trying to filter a list of tuples in haskell. 我正在尝试过滤haskell中的元组列表。 I want to return the tuples where the first and the second element are the same. 我想返回第一个和第二个元素相同的元组。

I'm trying this one 我正在尝试这个

 filter ((==fst).snd) [(1,2), (2,2), (3,3)] 

but it doesn't work. 但这不起作用。 Any ideas on this? 有什么想法吗? Thank you! 谢谢!

You can use uncurry : 您可以使用uncurry

filter (uncurry (==)) [(1,2), (2,2), (3,3)]

alternatively you can match on each tuple: 或者,您可以在每个元组上进行匹配:

filter (\(x,y) -> x == y) [(1,2), (2,2), (3,3)]

Try this: 尝试这个:

filter (\p -> fst p == snd p) [(1,2), (2,2), (3,3)]

(==fst).snd means \\p -> snd p == fst , obviously this would not work. (==fst).snd表示\\p -> snd p == fst ,显然这是行不通的。 If you really do not want to use lambda abstraction, and want a pointless version, here is one way to achieve that (you need to import Control.Applicative first): 如果您确实不想使用lambda抽象,并且想要一个无意义的版本,则这是一种实现方法(您需要先导入Control.Applicative ):

filter ((==) <$> fst <*> snd) [(1,2), (2,2), (3,3)]

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

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