ergoforce
ergoforce

Reputation: 17

How do I create a list of lists of pairs ordered and grouped by the second elements?

sorteerOpY :: (Int, Int) -> [[(Int, Int)]]
sorteerOpY (x,y) = [[(a,b)]|b<-[0..y-1],a<-[0..x-1]]

This is what I have right now, sorteerOpY (2,3) results in:

[[(0,0)],[(1,0)],[(0,1)],[(1,1)],[(0,2)],[(1,2)]]

But this is what I want it to result in:

[[(0,0),(1,0)],[(0,1),(1,1)],[(0,2),(1,2)]]

What do I need to change so that my list gets created correctly?

Upvotes: 1

Views: 104

Answers (1)

Zeta
Zeta

Reputation: 105886

You can think of list comprehensions as [[(a, b) | b <- [0..y-1]]| a<-[0..x-1]] like this:

for every b <- [0..y-1]       
   xs <- for every a <- [0..x-1]
      add (a, b) to the resulting list
   add xs to the resulting list

So if a in (a, b) should change faster, you need to swap those lines:

for every a <- [0..x-1]
   xs <- for every b <- [0..y-1]
      add (a, b) to the resulting list
   add xs to the resulting list

which directly results in [[(a,b) | a <- [0..x-1]]| b <- [0..y-1]].

Upvotes: 1

Related Questions