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

Lorenzo Bolla lbolla at gmail.com
Mon Nov 14 12:02:56 CET 2011


What about something like:

combinations n = filter (\s -> length s == n) . subsequences

hth,
L.



On Sun, Nov 13, 2011 at 10:42 PM, Peter Hall <peter.hall at memorphic.com>wrote:

> 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
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20111114/78658a4f/attachment.htm>


More information about the Beginners mailing list