在Haskell中生成列表的唯一组合的函数 [英] Function to generate the unique combinations of a list in Haskell

查看:73
本文介绍了在Haskell中生成列表的唯一组合的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个Haskell函数可以从列表中生成给定长度的所有唯一组合?

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]]

我尝试在Hoogle中查找,但是找不到专门用于执行此操作的函数。排列不能给出期望的结果。

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?

推荐答案

我也不知道预定义的函数,但是编写自己很容易:

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

这篇关于在Haskell中生成列表的唯一组合的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆