Prolog 问题 - 如何生成给定长度的子列表

发布于 2024-09-30 06:03:05 字数 612 浏览 5 评论 0原文

我想生成给定列表的所有子列表,具有给定的属性,它们具有作为参数提到的一定长度,并且它们还具有作为参数传递的给定元素作为包含元素。我已经设法做到了这一点,但在两个谓词的帮助下,并且在最优性方面非常慢:

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).

在这里我想通过 chooseT 参数返回> 谓词 L 列表中维度为 2 或 1 并且包含 f 元素的所有子列表。
谓词dimensionmember与预定义谓词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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅听莫相离 2024-10-07 06:03:05

以下构建长度的子序列 MinLen =<伦=<最大长度。我不知道你为什么重命名 lengthmember,所以我将使用原来的。 sublist/4 调用您的sublist/2

sublist(Sub,List,MinLen,MaxLen) :-
    between(MinLen,MaxLen,Len),
    length(Sub,Len),
    sublist(Sub,List).

请注意,length 是在两个变量上调用的,因此您将获得迭代加深搜索choose/2 现在可以定义为

choose(Sub,List) :-
    sublist(Sub,List,1,2),
    member(f,Sub).

这是干净的解决方案。如果不够快,则将所有条件合并到一个谓词中:

choose(Sub,List),
    (Sub = [f] ; Sub = [f,_] ; Sub = [_,f]),
    sublist(Sub,List).

The following builds subsequences of length MinLen =< Len =< MaxLen. I've no idea why you renamed length and member, so I'm going to use the originals. sublist/4 calls your sublist/2.

sublist(Sub,List,MinLen,MaxLen) :-
    between(MinLen,MaxLen,Len),
    length(Sub,Len),
    sublist(Sub,List).

Note that length is called on two variables, so you get an iterative deepening search. choose/2 can now be defined as

choose(Sub,List) :-
    sublist(Sub,List,1,2),
    member(f,Sub).

This is the clean solution. If it's is not fast enough, then roll all the conditions into one predicate:

choose(Sub,List),
    (Sub = [f] ; Sub = [f,_] ; Sub = [_,f]),
    sublist(Sub,List).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文