0

How can the elements of two lists be paired into tuples? Not just the first element of the first list with the first element of the second list, and so on. Every element of one list has to be (individually, pairs of 2) paired with every element of the other list, and vice-versa.

So, for two lists [1,2] and [3,4], we should get [(1,3),(1,4),(2,3),(2,4)]. Ideally, I would welcome any hints/solutions that do not include list generators (if solving this through list generators is possible).

I'm aware of the zip function, but as already mentioned, every element of one list has to be paired with every element of the other list. Thanks in advance

sandy
  • 33
  • 3

1 Answers1

1

The Applicative instance for lists does this.

> (,) <$> [1,2] <*> [3,4]
[(1,3),(1,4),(2,3),(2,4)]

(,) <$> [1,2] basically gives you a list of functions like [\x -> (1, x), \x -> (2, x)]. The <*> operator then ensures that each function in that list is applied each element of the other list.

chepner
  • 497,756
  • 71
  • 530
  • 681