谓词以查找术语中的子项的出现

时间:2017-04-07 01:10:30

标签: prolog

执行查询时,N的值为1而不是2:

出现(X,s(X,t(X,Y)),N)。 N = 1

occurrences(Sub,Term,R) :- occurrences(Sub,Term,0,R).
occurrences(Sub,Sub,Acc,R) :- R is Acc + 1.
occurrences(Sub,Term,Acc,R) :- functor(Term,_,N),occurrences(N,Sub,Term,Acc,R).
occurrences(N,Sub,Term,Acc,R4) :- N > 0, arg(N,Term,R),     occurrences(Sub,R,Acc,R2),
                               N1 is N-1, occurrences(N1,Sub,Term,R2,R4). 
occurrences(N,_,_,Acc,Acc) :- N < 1.

1 个答案:

答案 0 :(得分:2)

您已经在代码中查找正确的位置了。现在你只需要将它复制到最后。

http://eu.swi-prolog.org/pldoc/doc/swi/library/occurs.pl?show=src#occurrences_of_term/3

有关许可和版权信息,请参阅文件顶部。

http://eu.swi-prolog.org/pldoc/doc/swi/library/occurs.pl?show=src

occurrences_of_term(Sub, Term, Count) :-
    count(sub_term(Sub, Term), Count).

%!  occurrences_of_var(+SubTerm, +Term, ?Count)
%
%   Count the number of SubTerms in Term

occurrences_of_var(Sub, Term, Count) :-
    count(sub_var(Sub, Term), Count).

%!  sub_term(-Sub, +Term)
%
%   Generates (on backtracking) all subterms of Term.

sub_term(X, X).
sub_term(X, Term) :-
    compound(Term),
    arg(_, Term, Arg),
    sub_term(X, Arg).

%!  sub_var(-Sub, +Term)
%
%   Generates (on backtracking) all subterms (==) of Term.

sub_var(X0, X1) :-
    X0 == X1.
sub_var(X, Term) :-
    compound(Term),
    arg(_, Term, Arg),
    sub_var(X, Arg).


                 /*******************************
                 *              UTIL            *
                 *******************************/

%!  count(:Goal, -Count)
%
%   Count number of times Goal succeeds.

:- meta_predicate count(0,-).

count(Goal, Count) :-
    State = count(0),
    (   Goal,
        arg(1, State, N0),
        N is N0 + 1,
        nb_setarg(1, State, N),
        fail
    ;   arg(1, State, Count)
    ).