[Haskell-cafe] how can I select all the 3-element-combination out of a list efficiently

Jules Bean jules at jellybean.co.uk
Mon May 21 07:47:38 EDT 2007


haskell at list.mightyreason.com wrote:
> Then you want "triples1" from the code below.
> 
> The idea for triples1, triples2, and triples3 is that each pickOne returns a
> list of pairs.  The first element of each pair is the chosen element and the
> second element of each pair is the list of choices for the next element (given
> the current choice).

In the spirit of multiple implementations; another approach is to note 
that you're really asking for all 3-element sublists:

power [] = [[]]
power (x:xs) = power xs ++ map (x:) (power xs)

triples1' l = [ t | t <- power l, length t == 3]

(this implementation also preserves sorting)

Jules




More information about the Haskell-Cafe mailing list