1
>cprod [1,2,3] [’a’, ’b’]
[(1,’a’),(2,’a’),(3,’a’),(1,’b’),(2,’b’),(3,’b’)]

I try to implement the code by using zip but I know it is not enough. I also tried to use map but I just don't know how to start. Any tips or little help is appreciated.

John
  • 135
  • 6

2 Answers2

4

This is a use case for the [] monad (more specifically, the [] applicative functor). [] (as an applicative functor) encapsulates the idea of "try every possible combination of these things", i.e. a generalized Cartesian product.

flip (,) <$> ['a', 'b'] <*> [1, 2, 3]

If you don't care about the order, then you needn't worry about flipping

(,) <$> [1, 2, 3] <*> ['a', 'b']

Generally, zip (and the ZipList applicative functor) will join lists pairwise, so the first element matches the first, the second the second, and so on. The [] applicative functor will perform the Cartesian product, which is what you're looking for.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
3

List comprehension is another way to do this.

[(x, y) | y <- ['a', 'b'], x <- [1, 2, 3]]
hocho
  • 1,753
  • 1
  • 11
  • 14