Answer the question
In order to leave comments, you need to log in
How to prune a tree at a given depth in Prolog?
I want to prune a tree at a given depth. Arguments: arbitrary binary tree; required depth; resulting tree.
first(M,N):-
N>0,M=..[H|T],((T==[],write(H));(T\=[],write(H),Q is N-1,second(T,Q))).
second(M,N):-
N>0,M=[H|T],first(H,N),((T==[]);(T\=[],second(T,N)) ).
second(_,0):-!.
?- first(s(f(b(m,k),a),t(a,g)),4).
sfbmkatag
True
?- first(s(f(b(m,k),a),t(a,g)),2,X).
X = s(f,t)
True
?- first(s(f(b(m,k),a),t(a,g)),3,X).
X = s(f(b,a),t(a,g))
True
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question