[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 08:13:38 EDT 2007
Jules Bean wrote:
> 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)
...but is exponentially slower than necessary, and fails on infinite
lists. Try this one:
sublistsN 0 _ = [[]]
sublistsN n (x:xs) = map (x:) (sublistsN (n-1) xs) ++ sublistsN n xs
sublistsN _ _ = []
triples = sublistsN 3
BR,
--
-- Mirko Rahn -- Tel +49-721 608 7504 --
--- http://liinwww.ira.uka.de/~rahn/ ---
More information about the Haskell-Cafe
mailing list