Benny Abramovici
Benny Abramovici

Reputation: 582

nesting depth of a term

I'm trying to write a predicate to find the depth of nesting in a prolog term. for example : for an atom or variable the depth is zero. for f(a,b,1,2) the depth is 1. for f(a,b(7,a),1,2) the depth is 2, etc. here is what I have so far.

% base cases.

 get_depth(Term,0):-
  non_compound(Term),!.
 get_depth(Term,1):-
   Term =.. [_|T],
   all_basic(T),!. % no compound terms in list.
 get_depth(Term,Depth):-
 % this is where I need help.

 % helper prdeicates
  all_basic([T]):-
    non_compound(T),!.
  all_basic([H|T]):-
   non_compound(H),
   all_basic(T).

% term is non compound, either atomic or non instantiated variable.
non_compound(Term):-
 atomic(Term),!;
 var(Term).  

max(X,Y,X):-
 X >= Y,!.
max(_,Y,Y).

Upvotes: 1

Views: 80

Answers (1)

rajashekar
rajashekar

Reputation: 3793

depth(Term, D) :-
    Term =.. [_|Args],
    (  Args = []
    -> D = 0
    ;  maplist(depth, Args, Ds),
       max_list(Ds, D1), D is D1 + 1
    ).

If you do not want maplist and max_list

depth(Term, D) :-
    Term =.. [_|Args],
    (  Args = []
    -> D = 0
    ;  max_depth(Args, D1), D is D1 + 1
    ).

max_depth([Term], Max) :- depth(Term, Max).
max_depth([T1, T2| Rest], Max) :-
    depth(T1, D1), max_depth([T2 | Rest], M1),
    (D1 > M1 -> Max = D1; Max = M1).

Upvotes: 1

Related Questions