Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract all unique pairs of a list in Haskell? [duplicate]

Tags:

list

haskell

I am pretty new to Haskell and I have a question. How can I write a function to return all the unique possible pairs of a list? Like: [1,2,3,4] -> [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]

like image 880
Negar Alinaghi Avatar asked Dec 02 '15 13:12

Negar Alinaghi


3 Answers

Using a list comprehension is the easiest way.

import Data.List

pairs :: [a] -> [(a, a)]
pairs l = [(x,y) | (x:ys) <- tails l, y <- ys]

This only generates the relevant pairs so you don't have to filter out any duplicates as a separate step. tails [1,2,3,4] generates the lists of tails [[1,2,3,4], [2,3,4], [3,4], [4], []] and the list comprehension picks the first element from each tail and pairs it with the rest of the elements in that tail.

like image 135
shang Avatar answered Nov 04 '22 04:11

shang


Looking at your example, this seems to be what you want

unique_pairs l = [(x,y) | x <- l, y <- l, x < y]

By the way, these are not just unique pairs, but unique pairs up to transposition.

like image 21
lisyarus Avatar answered Nov 04 '22 04:11

lisyarus


You can use the nub function:

import Data.List
uniq_pairs l = nub [(x,y) | x <-l, y<-l, x < y]

Output:

*Main> uniq_pairs  [1,2,3,4]
[(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
like image 25
thor Avatar answered Nov 04 '22 04:11

thor