Prolog 问题 - 如何生成给定长度的子列表
我想生成给定列表的所有子列表,具有给定的属性,它们具有作为参数提到的一定长度,并且它们还具有作为参数传递的给定元素作为包含元素。我已经设法做到了这一点,但在两个谓词的帮助下,并且在最优性方面非常慢:
sublist([], []).
sublist([A|T], [A|L]):-
sublist(T, L).
sublist(T, [_|L]):-
sublist(T, L).
choose(T, L):-
sublist(T, L),
(dimension(2, T); dimension(1, T)),
belongs(f, T).
在这里我想通过 choose
的 T
参数返回> 谓词 L 列表中维度为 2 或 1 并且包含 f
元素的所有子列表。
谓词dimension
和member
与预定义谓词length
分别具有相同的用法member
。< br>
您能否告诉我如何将这两个条件合并到 sublist
谓词中,以便程序仅构建那些特定的子列表?
I want to generate all the sublists of a given list with the given property that they have a certain length mentioned as argument and also they have as a containing element a given element which is passed as a parameter. I have managed to do this but with the help of two predicates, and in terms of optimality is very slow:
sublist([], []).
sublist([A|T], [A|L]):-
sublist(T, L).
sublist(T, [_|L]):-
sublist(T, L).
choose(T, L):-
sublist(T, L),
(dimension(2, T); dimension(1, T)),
belongs(f, T).
In here I would like to return through the T
parameter of the choose
predicate all the sublists of the L list which have the dimension 2 or 1 and which contains the f
element.
The predicates dimension
and member
has the same usage as the predefined predicates length
, respectively member
.
Can you please tell me how to incorporate this two conditions within the sublist
predicate so that the program builds only those particular sublists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下构建长度的子序列
MinLen =<伦=<最大长度。我不知道你为什么重命名
length
和member
,所以我将使用原来的。sublist/4
调用您的sublist/2
。请注意,
length
是在两个变量上调用的,因此您将获得迭代加深搜索。choose/2
现在可以定义为这是干净的解决方案。如果不够快,则将所有条件合并到一个谓词中:
The following builds subsequences of length
MinLen =< Len =< MaxLen
. I've no idea why you renamedlength
andmember
, so I'm going to use the originals.sublist/4
calls yoursublist/2
.Note that
length
is called on two variables, so you get an iterative deepening search.choose/2
can now be defined asThis is the clean solution. If it's is not fast enough, then roll all the conditions into one predicate: