Recursion 当在prolog中递归时,可以访问n个级别以上的变量吗?

Recursion 当在prolog中递归时,可以访问n个级别以上的变量吗?,recursion,prolog,Recursion,Prolog,为了阐明我的意思,让我们以这个递归示例为例: statement([]). statement([A|B]):- A, statement(B). 头部A由规则my rules进行检查,尾部B被发送进行递归,然后成为级别2的头部。当它递归并处于第二级时,如何访问前一个A?我想的全错了吗?如果需要任何澄清,请询问,我会这样做。提前谢谢 我要测试的内容(类型检查器): 或 您必须显式地记录前面的语句,以便在每次迭代中都可以访问前面的步骤。这取决于你如何记录这些陈述。一种解决办法是: statem

为了阐明我的意思,让我们以这个递归示例为例:

statement([]). 
statement([A|B]):- A, statement(B).
头部A由规则my rules进行检查,尾部B被发送进行递归,然后成为级别2的头部。当它递归并处于第二级时,如何访问前一个A?我想的全错了吗?如果需要任何澄清,请询问,我会这样做。提前谢谢

我要测试的内容(类型检查器):


您必须显式地记录前面的语句,以便在每次迭代中都可以访问前面的步骤。这取决于你如何记录这些陈述。一种解决办法是:

statement(L) :- statement(L,[]).
statement([], _). 
statement([A|B], L):- check(A), statement(B,[A|L]).

L记录前面的语句(按相反顺序)。

当然。。使用prolog数据库,断言和收回。这表明:

% Declare the lasthead fact as dynamic, so facts can change
:-dynamic lasthead/1.

% Set a starting value for the first iteration
lasthead(null).

statement([]).
statement([A|B]) :-

    % Show the previous head
    lasthead(LH),
    writeln(['Last head was', LH]),

    % Retract last head. ie. remove from the database
    retract(lasthead(_)),

    % Store the current head in the database
    assertz(lasthead(A)),

    % Recurse around
    statement(B).


?- statement([a,b,c,d,e]).
[Last head was,null]
[Last head was,a]
[Last head was,b]
[Last head was,c]
[Last head was,d]
上面的示例使用retract来确保只有一个lasthead(X)事实,但是您可以删除retract,这将确保有多个lasthead(X)事实,每个列表项一个


然后,您可以使用findall(X,lasthead(X),Y)访问/处理多个lasthead(X)事实,这将为您提供沿途断言的lasthead(X)值。

将其作为参数传递有什么不对?声明(B,A),因为我将向其发送一份列表。我将添加我想检查的内容。我当然会采纳一个更好的方法的建议。唯一的问题是,我不确定是否会有比我将要展示的更多的测试。传递给statement()的列表元素是令牌?我实际上不确定令牌。例如语句([instance(string,s),instance(int,z),equals(i,method(s,length)))。希望这能有所帮助。如果没有,那么我可以用一个更详细的例子发布它。正如你所看到的,如果我在一个列表中有这个,递归它最终会失去我目前所做的统一,或者至少我认为这是应该发生的事情。这可能不是对
assertz/1
的恰当使用,但当人们没有任何评论时,我觉得很烦人。我同意,对答案的问题进行精心设计的评论会对网站及其读者有更大的帮助。不太完美的答案提供了将它们与最好的答案进行比较和对比的可能性,对每个人都有帮助。
statement(L) :- statement(L,[]).
statement([], _). 
statement([A|B], L):- check(A), statement(B,[A|L]).
% Declare the lasthead fact as dynamic, so facts can change
:-dynamic lasthead/1.

% Set a starting value for the first iteration
lasthead(null).

statement([]).
statement([A|B]) :-

    % Show the previous head
    lasthead(LH),
    writeln(['Last head was', LH]),

    % Retract last head. ie. remove from the database
    retract(lasthead(_)),

    % Store the current head in the database
    assertz(lasthead(A)),

    % Recurse around
    statement(B).


?- statement([a,b,c,d,e]).
[Last head was,null]
[Last head was,a]
[Last head was,b]
[Last head was,c]
[Last head was,d]