简体   繁体   English

在Prolog中建立递归列表

[英]Recursive list building in prolog

I'm trying to write a rule in prolog that requires me to build a list recursively. 我正在尝试在序言中写一条规则,要求我递归建立一个列表。 I'm being able to build that list but the issue is that I dont know how to stop that process for building the list. 我能够构建该列表,但是问题是我不知道如何停止构建列表的过程。 So, I need to write a rule that would stop building that list further. 因此,我需要编写一条规则,以停止进一步构建该列表。

This is what my rule looks like: 这是我的规则:

%a few rules that are supplementing the rule popular:

member(H,[H|T]).
member(X,[H|T]) :- member(X,T).

notmember(H,A) :- member(H,A), !, fail.
notmember(H,A).

size([],0).
size([H|T],N) :- size(T,N1), N is N1+1.

listhasx(X,A) :- article(A,_,_,_,R), member(X,R).

notlisthasx(X,A) :- listhasx(X,A), !, fail.
notlisthasx(X,A).

makelist(A,L) :- ________________________________________________________.
makelist(A,L) :- listhasx(X,B), notmember(B,L), N2 is B, makelist(N2,L2), L=[A|L2].

popular(X,0).
popular(X,N) :- listhasx(X,A), makelist(A,L), size(L,N1), N-1<N1.

So, basically, I need to write a rule for popular, which I have written already. 因此,基本上,我需要为流行写一个规则,我已经写了。 But, it uses the makelist rule which is partially incomplete. 但是,它使用了部分不完整的makelist规则。 To be specific, the first part of makelist needs to be completed, which would imply when the list should be stopped from building. 具体来说,makelist的第一部分需要完成,这意味着应该在何时停止构建列表。

I would be really thankful if someone could help me out on this.. 如果有人可以帮助我,我将非常感激。

The easiest way to build a list of X such that they satisfy a goal G, is to use the findall predicate. 建立X列表以使其满足目标G的最简单方法是使用findall谓词。 Here is an example: 这是一个例子:

?- [user].
p(3).
p(1).
p(2).
^D
Yes
?- p(X).
X = 3 ;
X = 1
?- findall(X, p(X), L).
L = [3, 1, 2]

The predicate finall/3 is part of the ISO core standard. 谓词finall / 3是ISO核心标准的一部分。 So should be found in most Prolog systems. 因此应该在大多数Prolog系统中找到。 Related predicates are bagof/3 and setof/3. 相关谓词是bagof / 3和setof / 3。

Also useful are predicates from a module aggregate found in many Prolog systems, or solution counting and limiting predicates also found in many Prolog systems. 来自许多Prolog系统中的模块集合的谓词或许多Prolog系统中也存在的解决方案计数和限制谓词也很有用。

Bye 再见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM