Iterate over all combinations of pairs without repeating in Haskell

The haskell defined by the xs element list is the easiest way to iterate over all paired permutations with repetitions:

 [(x,y) | x <- xs, y <- xs] 

I want to be able to do the same, but only in combination. If x and y were comparable, I could do

 [(x,y) | x <- xs, y <- xs, x > y] 

But I would prefer the solution to be more general and more efficient (I know that the asymptotic complexity will remain squared, but we can halve the actual complexity of the execution by avoiding the use of the filter condition)

+6
source share
2 answers

What about:

 [ (x,y) | (x:rest) <- tails xs , y <- rest ] 
+15
source

If I copy and simplify Math.Combinat.Sets.choose for a particular case k=2 , it gives

 pairs :: [a] -> [[a]] pairs [] = [] pairs (x:xs) = map (\y -> x:[y]) xs ++ pairs xs -- replace with \y -> (x,y) to get 2-tuples >>> pairs [1,2,3] [[1,2],[1,3],[2,3]] 
0
source

Source: https://habr.com/ru/post/981665/


All Articles