:- module(_,_).

% Example of Structure Inspection: Subterm
% subterm(Sub,Term): Sub is a subterm of Term

subterm(Term,Term).  % a) A term is always a subterm of itself
subterm(Sub,Term):-  % b) The arguments are also subterms:
    nonvar(Term),    %    Check Term not a free variable
    functor(Term,_F,N),%  N is the number of arguments of Term
    n_to_one(N, J),  %    J is a natural between N and 1
    arg(J,Term,Arg), %    Arg is the J-th argument of Term
    subterm(Sub,Arg).%    Sub are the subterms of Arg

n_to_one(N, N) :- N > 0.
n_to_one(N, X) :- N > 1, N1 is N-1, n_to_one(N1, X).

% Try (asking also for other solutions): 
% ?- subterm( f(a) , g(b,f(a)) ).
% ?- subterm( f(b) , g(b,f(a)) ).
% ?- subterm( g(b,f(a)) , g(b,f(a)) ).
% ?- subterm( X , g(b,f(a)) ).
% ?- subterm( f(X) , g(b,f(a)) ).
% ?- subterm( X , g(X,f(a)) ).
% ?- subterm( f(X) , g(b,f(X)) ).
