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

Mirko Rahn rahn at ira.uka.de
Mon May 21 09:07:31 EDT 2007


Mark T.B. Carroll wrote:

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

No! With this implementation we have nOf 0 _ == [] but it should be nOf 
0 _ == [[]]: The list of all sublists of length 0 is not empty, it 
contains the empty list!

Correct (and more natural):

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

BR,

-- 
-- Mirko Rahn -- Tel +49-721 608 7504 --
--- http://liinwww.ira.uka.de/~rahn/ ---


More information about the Haskell-Cafe mailing list