Function to generate the unique combinations of a

2019-08-24 10:03发布

问题:

Is there a Haskell function that generates all the unique combinations of a given length from a list?

Source = [1,2,3]

uniqueCombos 2 Source = [[1,2],[1,3],[2,3]]

I tried looking in Hoogle but could not find a function that did this specifically. Permutations does not give the desired result.

Has anybody used a similar function before?

回答1:

I don't know a predefined function either, but it's pretty easy to write yourself:

-- Every set contains a unique empty subset.
subsets 0 _ = [[]]

-- Empty sets don't have any (non-empty) subsets.
subsets _ [] = []

-- Otherwise we're dealing with non-empty subsets of a non-empty set.
-- If the first element of the set is x, we can get subsets of size n by either:
--   - getting subsets of size n-1 of the remaining set xs and adding x to each of them
--     (those are all subsets containing x), or
--   - getting subsets of size n of the remaining set xs
--     (those are all subsets not containing x)
subsets n (x : xs) = map (x :) (subsets (n - 1) xs) ++ subsets n xs


回答2:

Using Data.List:

import Data.List
combinations k ns = filter ((k==).length) $ subsequences ns

Reference: 99 Haskell Problems

There's quite a few interesting solutions in the reference, I just picked a concise one.



回答3:

There is no such operation in lib, but you can easily implement it yourself:

import Data.List

main = putStrLn $ show $ myOp 2 [1, 2, 3]

myOp :: Int -> [a] -> [[a]]
myOp 0 _ = []
myOp 1 l = map (:[]) l
myOp c l = concat $ map f $ tails l
    where
        f :: [a] -> [[a]]
        f []     = []
        f (x:xs) = map (x:) $ myOp (c - 1) xs