How do I re-express a list comprehension with two generators to two list comprehensions with one generator each and get the same result?

Viewed 526

I'm trying to learn Haskell, and I'm doing some exercises that involves lists. But I'm struggling with an exercise about list comprehension, and I really need someone to help me with this. The exercise reads:

Show how the list comprehension [(x,y) | x <- [1,2], y <- [3,4]] with two generators can be re-expressed using two comprehensions with single generators.

Hint: nest one comprehension within the other and make use of the library function concat :: [[a]] -> [a].

I appreciate all answers and explanations. Thanks.

1 Answers

First, you can generate [1, 2] using [x | x <- [1, 2]].

Now, for each x, you want to have (x, 3) and (x, 4) instead of just x. So let's replace it with a list comprehension. Then you'll get [[(x, y) | y <- [3, 4]] | x <- [1, 2]].

But this gives you [[(1,3),(1,4)],[(2,3),(2,4)]] because you converted each x to [(x, 3), (x, 4)]. As the hint suggests, you can use concat to squash them.

To put it together, you'll get concat [[(x, y) | y <- [3, 4]] | x <- [1, 2]].

Related