[Haskell-beginners] Combinations of choosing n items from a list

Peter Hall peter.hall at memorphic.com
Sun Nov 13 23:42:25 CET 2011


Hi all,
This function took me a long time to write, getting my head around the
double recursion. It returns a list of all possible sub-sets of a
given length from a list.

I have a couple of questions.

1. Can it be improved for efficiency or style?
2. Is there a library that already has this and other related
functions? I assumed there would be but I couldn't find it on hoogle.


combinations :: Int -> [a] -> [[a]]
combinations _ [] = []
combinations 0 _ = []
combinations 1 x = map (:[]) x
combinations n (x:xs) = (map (x:) $ combinations (n-1) xs) ++ combinations n xs

e.g.
> combinations 3 [1..5]
[[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]]

Thanks,
Peter



More information about the Beginners mailing list