user2585677
user2585677

Reputation: 149

Use =.. to define the predicate subterm(T1,T2)

I want to review my lessons quickly by doing some practice. But I have no solution for those practice to check. Could you give me a solution, so when I get stucke. I could find some guidance here quickly.The first question is described below. Thanks in advance.

Question1. We recall that the built in predicate T =.. L is satisfied if T is a term and L is the list that contains the functor and the main subterms of L. For example, f(a,g(b)) =.. L is satisfied when L = [ f, a, g(b) ],and a =.. List is satisfied when List = [a].

Use =.. to define the predicate subterm(T1,T2) which is satisfied when T1 is a subterm of T2. You may assume that T1 and T2 have no variables. You may also want to use the built in predicates atomic(X) or compound(X) that check if X is an atomic term and a structure, in this order.

My solution is:

subterm(X,[X]):-atom(X),!.
subterm(T1,T2):-
compound(T1),
T1=..U,
U=[X|Y],
T2=Y.

Any advice will be appreciated. Thanks!

Upvotes: 1

Views: 528

Answers (1)

CapelliC
CapelliC

Reputation: 60034

If a term T is a subterm of itself, the definition can be very simple:

subterm(T, T).
subterm(T1, T2) :-
  T2 =.. [_|As],
  member(A, As),
  subterm(T1, A).

Anyway, you can see as the predicate above implements a 'lazy' visit of the tree structured term.

Upvotes: 1

Related Questions