gnu Prolog powerset 修改
所以我得到了这个 powerset:
powerset([], []).
powerset([H|T], P) :- powerset(T,P).
powerset([H|T], [H|P]) :- powerset(T,P).
这会生成列表的所有集合。是否可以按列表顺序生成所有集合。
示例:
List = [a,b,c]
我想得到
[a],[a,b],[a,b,c],[b],[b,c],[c]
注意,此子集列表中没有 [a,c]
因为这些子集是从左侧开始向右的。
我尝试过使用追加和递归的组合,但这并没有达到我想要的效果。此时小小就愣住了。
谢谢。
So i got this for powerset:
powerset([], []).
powerset([H|T], P) :- powerset(T,P).
powerset([H|T], [H|P]) :- powerset(T,P).
This generates all sets of a list. Is it possible to generate all sets in list order.
Example:
List = [a,b,c]
I want to get
[a],[a,b],[a,b,c],[b],[b,c],[c]
Note there is no [a,c]
in this list of subsets since these are subsets starting from the left and going to the right.
I've tried using a combination of append and recursion, but that didn't work out as i wanted it to. Little stumped at this point.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样
How about
我知道这是一篇旧文章,但我不会无缘无故地更新它。
得到所有尊重的答案,单独生成所有子集,并且不生成幂集。
几天前,我试图实现一个
powerSet/2
谓词,而不使用内置谓词bagof/2
。但即使使用 bagof/2 和 setof/2 对于初学者来说这也不是一个很容易的问题(单独生成所有子集是另一个问题,而且要容易得多)。因此,在实现该解决方案之后,我认为最好将其放在这里,以防止正在搜索该主题的人出错。我的解决方案(没有
bagof/2
)如果参考注释行,
代码将会被理解。 此处提供了另一种解决方案,它使用内置谓词
bagof/3
。也许现在会更有帮助。
I know this an old post, but I'm not gonna update it for no reasons.
the answer which is accepted with all the respect, generates all subsets separably, and does not generate a powerset.
a few days ago I was trying to implement a
powerSet/2
predicate, without use of built-in predicatebagof/2
. but even withbagof/2
andsetof/2
it's not very easy problem for beginners (generating all subset separably is another problem and much easier). so after implementing the solution I thought it's better to put it here in order to prevent people who are searching for this topic from mistakes.My solution (without
bagof/2
)code will be understood if consulted with the commented lines.
another solution is available here which uses built-in predicate
bagof/3
.probably it would be more helpful now.
您需要所有
子序列子字符串(定义)。语法(DCG)最适合这个:You want all
subsequencessubstrings (definition). Grammars (DCGs) are best for this:这个怎么样:
How about this: