问题描述:

How to create such a list comprehension that given

[(i,j) | i <- [1..4], j <- [1..4]] yields the following:

[(1,1),(2,1),(3,1),(4,1),(2,2),(3,2),(4,2),(3,3),(4,3),(4,4)]

i.e. listing all the combinations with respect to j?

PS. Swapping the places of "i" and "j" isn't the solution I am looking for.

网友答案:

Since in your desired output the first component is always at least as large as the second, let i start from j, instead of from 1:

[(i,j) | j <- [1 .. 4], i <- [j .. 4]]

With the j <- [1 .. 4] generator first, the j is in scope and can be used for the i generator.

网友答案:

You can also use a boolean guard:

[(i,j) | i <- [1..4], j <- [1..4], i >= j]
相关阅读:
Top