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

Mark T.B. Carroll mark at ixod.org
Mon May 21 08:05:31 EDT 2007


geniusfat <ken at tzi.de> writes:
(snip)
> the order does not matter and each object can be chosen only once.
(snip)

In that case, with the help of Data.List.tails, one can do:

threeOf :: [a] -> [(a,a,a)]

threeOf xs =
    [ (p,q,r) | (p:ps) <- tails xs, (q:qs) <- tails ps, r <- qs ]

(the r <- qs is a simpler version of (r:rs) <- tails qs)

or maybe,

nOf :: Int -> [a] -> [[a]]

nOf _    []  = []
nOf 1    xs  = map return xs
nOf n (x:xs) = map (x:) (nOf (n-1) xs) ++ nOf n xs

(These are fairly naive versions that just took me a few minutes, but
perhaps they'll do.)

-- Mark



More information about the Haskell-Cafe mailing list