简体   繁体   English

如何只从元组列表中获取我想要的元组? [哈斯克尔]

[英]How to only get the tuples I want from a list of tuples? [Haskell]

I'm trying to set up a list of tuples from a list of Integers in this form: (a,b) a <- [1..4] and b <- xs.我正在尝试从以下形式的整数列表中设置元组列表:(a,b) a <- [1..4] 和 b <- xs。 But I keep getting all the different combinations of the statement.但是我不断得到语句的所有不同组合。

okTup :: [Int] -> [(Int,Int)]
okTup xs = [(i,j) | i <- [1..4], j <- xs]

Input: okTup [3,1,4,2]输入:okTup [3,1,4,2]

What I get is this: [(1,3),(1,1),(1,4),(1,2),(2,3),(2,1),(2,4),(2,2),(3,3),(3,1),(3,4),(3,2),(4,3),(4,1),(4,4),(4,2)]我得到的是:[(1,3),(1,1),(1,4),(1,2),(2,3),(2,1),(2,4),( 2,2),(3,3),(3,1),(3,4),(3,2),(4,3),(4,1),(4,4),(4, 2)]

But I only want this: [(1, 3 ),(2, 1 ),(3, 4 ),(4, 2 )]但我只想要这个: [(1, 3 ),(2, 1 ),(3, 4 ),(4, 2 )]

That's zip :那是zip

okTup xs = zip [1..] xs

If you prefer to do this with a list comprehension, or you want to extend an existing comprehension, you can use the ParallelListComp extension, which allows you to write:如果您更喜欢使用列表推导式执行此操作,或者您想扩展现有推导式,您可以使用ParallelListComp扩展,它允许您编写:

okTup xs = [(i, j) | i <- [1..] | j <- xs]

(Note the vertical bar | instead of a comma , .) (注意竖线|而不是逗号, 。)

Of course, this essentially just uses zip under the hood.当然,这基本上只是在引擎盖下使用zip

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

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