Haskell中列表的元素的子集 [英] Subsets of elements of a list in Haskell

查看:173
本文介绍了Haskell中列表的元素的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如:如果我有[2,3,4]并且如果我想要K = 2,这意味着我需要两对=> [[2,3],[3,2],[2,4],[4,2],[3,4],[4,3]], p>

我编写了这段代码,但它只生成子集的数量:

  arrange :: Int-> Int-> Int 
arrange n 1 = n
arrange nr = n * arrange(n-1)(r-1)

另一个版本,但这不会生成所有子集的解决方案:

(arrange n xs)


解决方案基于你的例子,这是一个可能的解决方案:
$ b $ $ p $ import Data.List(permutations)

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

arrange :: Int - > [a] - > [[a]]
安排n = concatMap排列。选择n



示例



 λ>安排2 [2,3,4] 
[[2,3],[3,2],[2,4],[4,2],[3,4],[4,3]]

你可以看到诀窍就是挑选一些元素,然后获得结果的所有排列(使用 concatMap 将它们连接在一起)



当然,这可能是功课,所以你可能想实现 permutations 自己;)


Can anyone help me to generate all the subsets of a given set?

Example:If I have [2,3,4] and if I want K=2, that means I need pairs of two => [[2,3], [3,2], [2,4], [4,2], [3,4], [4,3]]

I wrote this code, but it generates only the number of subsets:

arrange::Int->Int->Int
arrange n 1=n
arrange n r=n*arrange (n-1) (r-1)

Another version, but this doesn't generate all solutions of the subsets:

  arrange 0 _ =[[]]
  arrange _ []=[]
  arrange n (x:xs)=(map(x:)) (arrange (n-1) xs)++
                   (arrange n xs)

解决方案

Well based on your example this is a possible solution:

import Data.List (permutations)

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

arrange :: Int -> [a] -> [[a]]
arrange n = concatMap permutations . pick n

example

λ> arrange 2 [2,3,4]
[[2,3],[3,2],[2,4],[4,2],[3,4],[4,3]]

as you can see the trick is just picking a number of elements and then getting all permutations of the results (using concatMap to concat them together)

of course this might be homework so you might want to implement permutations by yourself ;)

这篇关于Haskell中列表的元素的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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