S
S
Sergey_88882018-06-16 23:47:07
Prolog
Sergey_8888, 2018-06-16 23:47:07

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):-!.

I wrote a program that gives me this result.
?- first(s(f(b(m,k),a),t(a,g)),4).
sfbmkatag
True

But I need to get this result.
?- 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

Please someone tell me how to do this. Not necessarily on Visual, you can on Turbo.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question