列表理解:列出列表 [英] List comprehension: making lists of lists

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

问题描述

嗨im试图在haskell中使用数字a的一个函数使用列表的一个部分,例如数字 4 它会创建 [[1,1,1,1],[1,1,2],[1,3],[2,2],[4]] 。我正在考虑使用列表理解来创建列表x,然后使用[1 ... n]中的数字(n是我想要的分区编号)创建更多列表,其中创建列表的总和相等到n。

hi im trying to make a function in haskell that takes a number a makes a partion of it using lists i.e. for number 4 it would create [[1,1,1,1],[1,1,2],[1,3],[2,2],[4]]. I was thinking of using list comprehension for this where it would create list x and then create further lists using numbers from [1...n] (n being the partition number I would want) where the sum of the list created would be equal to n.

到目前为止我创建的代码是 -

The code I have created so far is-

partions (n:xs) = [[x|x<-[1...n], sum[x]==n]]|xs<-[1..]]

但很明显它不起作用,有什么建议吗?

but obiviously it doesnt work, any suggestions?

谢谢。

推荐答案

我建议尝试递归:要获得n的分区,遍历数字i = 1到n,并递归地生成分区(ni),基本情况是1的唯一分区本身是1,0的分区是空列表。

I suggest trying recursion: To obtain the partitions of n, iterate over the numbers i = 1 to n, and recursively generate the partitions of (n-i), the base case being that the only partition of 1 is 1 itself, and the partition of 0 is the empty list.

这篇关于列表理解:列出列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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