问题
Arguments: arbitrary binary tree; necessary depth; result tree.
Result:
?- pred(s(f(b(m,k),a),t(a,g)),2,X).
X = s(f,t) yes
?- pred(s(f(b(m,k),a),t(a,g)),3,X).
X = s(f(b,a),t(a,g)) yes
?-
Can someone help me with it?
回答1:
Let's rearrange your examples:
?- pred( s( f(b(m,k),a), t(a,g)), 3, X).
X = s(f(b,a),t(a,g)) yes
?- pred( s( f(b(m,k),a), t(a,g)), 2, X).
X = s(f,t) yes
?- pred( s( f(b(m,k),a), t(a,g)), 1, X).
X = s yes
?- pred( s( f(b(m,k),a), t(a,g)), 0, X).
no
Now it's clear what needs to be done, isn't it?
Another piece to this puzzle is the so-called "univ" predicate, =..,
9 ?- s( f(b(m,k),a), t(a,g)) =.. [A, B, C].
A = s,
B = f(b(m, k), a),
C = t(a, g).
10 ?- X =.. [s, f(b(m,k),a), t(a,g)].
X = s(f(b(m, k), a), t(a, g)).
11 ?- X =.. [s, f(b,a), t(a,g)].
X = s(f(b, a), t(a, g)).
12 ?- X =.. [s, f, t].
X = s(f, t).
13 ?- X =.. [s].
X = s.
14 ?- s =.. X.
X = [s].
That's how you can take apart your data, and build it up again.
Lastly, you will need to use recursion:
recursion( In, Out) :-
base_relation( In, Out).
recursion( In, Out) :-
constituents( In, SelfSimilarParts, LeftOvers),
maplist( recursion, SelfSimilarParts, InterimResults),
constituents( Out, InterimResults, LeftOvers).
来源:https://stackoverflow.com/questions/50871893/trim-the-tree-at-the-specified-depth-in-prolog