WormyQuilt
WormyQuilt

Reputation: 31

Counting occurrences of a subterm in a term in prolog

I'm trying to write a predicate in prolog called occurrences(Sub, Term, N) that will return true if N is the number of occurrences of Sub in Term. I'm using SWI-prolog and I found this built-in predicate called contains_term(Sub, Term) that is true if Sub is contained in Term. So I'm trying count the number of times contains_term is true and make that be the N in the occurrences predicate.The problem is I'm not quite sure how to do this, and the fact that contains_term is a predefined predicate makes it harder to figure out. Any help would be appreciated.

Upvotes: 2

Views: 594

Answers (1)

false
false

Reputation: 10102

term_subterm_n(T, S, N) :-
   bagof(t, term_subterm(T,S), Ts),
   length(Ts, N).

term_subterm(T, T).
term_subterm(T, S) :-
   compound(T),
   T =.. [_|Es],
   member(E, Es),
   term_subterm(E, S).

Upvotes: 2

Related Questions