简体   繁体   中英

Confused about recursive counters in Prolog

I have been stuck on this problem for a couple of days. So given a balanced tree of the form t(Tree, Value, Tree), I want to find the depth of the left tree, which I did with the following code:

depthLeft(nil, 1).
depthLeft(t(Tree1, _, _), N) :-
    depthLeft(Tree1, N1),
    N is N1 + 1.

So the code works but I'm very confused at the counter. Firstly why can't you put the counter above the recursive call? Secondly why can't you argue that N1 is N - 1 instead like here to return the nth element of a list:

element_at(X,[X|_],1).
element_at(X,[_|L],K) :- K > 1, K1 is K - 1, element_at(X,L,K1).

I fail to see why the counters have a different logic here. If anyone could point me in the direction it would be greatly appreciated.

Firstly why can't you put the counter above the recursive call?

Because it doesn't work if you do that; Prolog isn't magic, it functions in a way that works on real computers, a way that was simple enough for computers of the 1970s - line by line, from the top:

depthLeft(t(Tree1, _, _), N) :-    % this holds if
    N is N1 + 1.                   % (calculate N1 + 1, error, N1 has no value).
    depthLeft(Tree1, N1),          % stopped before getting here.

Secondly why can't you argue that N1 is N - 1 instead like here to return the nth element of a list:

That goes the other way, you provide K as the index of the element you desire so K-1 can be calculated as soon as that code is reached. If you want to feed in "does my tree have depth 4?" then you can rearrange so N1 can have a value but that's a different question to "what is the depth of my tree?".

You either count from zero, increasing as you descend into the tree, stopping at the end, in a tail recursive way (no remaining work), and return the final count. Or you descend into the tree knowing nothing, pending the addition work for later until you reach to the end, count 1 there, then ascend back out through the callstack doing all the pending additions until you get back to the start with your answer. This way is often simpler to write but eats more memory and performs worse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM