Kushagra Kumar
Kushagra Kumar

Reputation: 43

Predicate to find occurrences of subterm in a term

While executing the query, value of N was coming out to be 1 instead of 2:

occurrences(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.

Upvotes: 1

Views: 246

Answers (1)

user7473772
user7473772

Reputation:

You are already looking at the right place in the code. Now you only need to copy it to the end.

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

See the top of the file for licence and copyright info.

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

Upvotes: 2

Related Questions