Trim the tree at the specified depth. In Prolog

微笑、不失礼 提交于 2019-12-13 08:21:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!