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

Jules Bean jules at jellybean.co.uk
Sun May 20 08:28:58 EDT 2007


geniusfat wrote:
> hi dear haskell lover ;)
> what I want to do is simply this:
> select3 :: [a] -> [(a, a, a)]
> and how can it be done efficiently?
> thanks in advance!


If, given [1,2,3,4,5,6,7,8,9,10,11,12] you want 
[(1,2,3),(4,5,6),(7,8,9)....] then:

map (take 3) . iterate (drop 3)

is very nearly what you need.

Two problems: (a) it gives you [[1,2,3],[4,5,6]..] instead
(b) it carries on with an infinite number of [] empty lists

you can fix both of these:

map (\[a,b,c]->(a,b,c)) . takeWhile (not.null) . map (take 3) . iterate 
(drop 3)

Prelude> map (\[a,b,c] -> (a,b,c)) . takeWhile (not.null) . map (take 3) 
. iterate (drop 3) $ [1..12]
[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]


Hope that helps.

Jules



More information about the Haskell-Cafe mailing list