In today’s Programming Praxis exercise, our goal is to produce all combinations of two elements of a list, without duplicates. Let’s get started, shall we?
The basic idea is pretty simple: we start with the first element and make all combinations with the other ones. Since that element is now no longer needed, we can remove it and repeat the process for the rest of the list.
pairs :: [a] -> [(a, a)] pairs xs = [(a,b) | (a:bs) <- tails xs, b <- bs]
Some tests to see if everything is working properly:
main :: IO () main = do print $ pairs [1..4] print $ length (pairs [1..4]) == 6 print $ pairs [1..6] print $ length (pairs [1..6]) == 15 print $ pairs [1..16] print $ length (pairs [1..16]) == 120