ruu*_*bel -2 haskell tuples list-comprehension
我试图以这种形式从整数列表中设置一个元组列表:(a,b)a < - [1..4]和b < - xs.但我不断得到声明的所有不同组合.
okTup :: [Int] -> [(Int,Int)]
okTup xs = [(i,j) | i <- [1..4], j <- xs]
Run Code Online (Sandbox Code Playgroud)
输入:okTup [3,1,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)]
但我只想这样:[(1,3),(2,1),(3,4),(4,2)]
那是zip:
okTup xs = zip [1..] xs
Run Code Online (Sandbox Code Playgroud)
如果您希望使用列表推导执行此操作,或者您希望扩展现有的理解,则可以使用ParallelListComp扩展名,这允许您编写:
okTup xs = [(i, j) | i <- [1..] | j <- xs]
Run Code Online (Sandbox Code Playgroud)
(注意垂直条|而不是逗号,.)
当然,这基本上只是zip在引擎盖下使用.