size of tree using accumulator

放肆的年华 提交于 2019-12-24 01:48:16

问题


I am tryin to learn prolog and got stuck in one of the toy example. binary_tree is defined as:

The term '-' (the minus symbol) represents the empty tree. The term t(L,V,R) represents a tree with left subtree L, node value V, and right subtree R.

now Im trying to write the predicate size(Tree,N) to find the size of tree. I know it is possible using the following :

size( -,0).
size( t(L, _,R), S) :- size(L,Ls), size(R,Rs), S is Ls + Rs + 1.

but I want to make it work using accumulator. I tired something like(and some other stuffs) but none is working:

size(t(L,_,R),N):-size(t(L,_,R),0,N).

size(-,A,A).
size(t(L,_,R),A,N):- A1 is A+1,size(L,A1,N1),size(R,A1,N2), N is N1+N2.

for example for test case:

size(t(-,n,t(-,m,-)),N).

I get 5 instead of 2. here is the trace:

[debug] [7] 85 ?- trace,size(t(-,n,t(-,m,-)),N).
   Call: (73) size(t(-, n, t(-, m, -)), _G10307) ? creep
   Call: (74) size(t(-, _G10422, t(-, m, -)), 0, _G10307) ? creep
   Call: (75) _G10435 is 0+1 ? creep
   Exit: (75) 1 is 0+1 ? creep
   Call: (75) size(-, 1, _G10437) ? creep
   Exit: (75) size(-, 1, 1) ? creep
   Call: (75) size(t(-, m, -), 1, _G10437) ? creep
   Call: (76) _G10438 is 1+1 ? creep
   Exit: (76) 2 is 1+1 ? creep
   Call: (76) size(-, 2, _G10440) ? creep
   Exit: (76) size(-, 2, 2) ? creep
   Call: (76) size(-, 2, _G10440) ? creep
   Exit: (76) size(-, 2, 2) ? creep
   Call: (76) _G10441 is 2+2 ? creep
   Exit: (76) 4 is 2+2 ? creep
   Exit: (75) size(t(-, m, -), 1, 4) ? creep
   Call: (75) _G10307 is 1+4 ? creep
   Exit: (75) 5 is 1+4 ? creep
   Exit: (74) size(t(-, _G10422, t(-, m, -)), 0, 5) ? creep
   Exit: (73) size(t(-, n, t(-, m, -)), 5) ? creep
N = 5.

I feel I need to have two different accumulator but not sure how do that.I would appreciate any explanation (rather than straight answer) since I am trying to learn this stuff.


回答1:


You are counting subtrees twice:

size(t(L,_,R),A,N):- A1 is A+1,size(L,A1,N1),size(R,A1,N2), N is N1+N2.
                                      ^^            ^^      ^^^^^^^^

The value A1 is used twice. What you actually want is to describe a difference (not a difference list but something very similar).

size(-, N,N).            % N-N   ... 0
size(t(L,_,R), N0,N) :-  % N-N0  ... the total size
   N1 is N0+1,           % N1-N0 ... 1
   size(L, N1,N2),       % N2-N1 ... size of L
   size(R, N2,N).        % N-N2  ... size of R

Please remark the pattern for the variables. The first is N0 and the last is N. They are spread almost shoelace-like.



来源:https://stackoverflow.com/questions/24714985/size-of-tree-using-accumulator

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