height
is not a function that returns the height. It is a predicate
that is true when the second argument is the height of the first argument. So you can use height(L,_) > height(R,_)
. You have to do height(L,LH), height(R,RH)
and compare LH
with RH
. For similar reasons, you cannot query height(L, H-1)
and get expected results since, as @false points out, H-1
is the term '-'(H,1)
in this context, and is not interpreted as an arithmetic expression. In Prolog, an arithmetic expression is only interpreted when it's on the right hand side of an is
expression, or is in an arithmetic comparison expression.
So in full, your corrected predicate looks like:
height( nil, 0 ). % Height of nil tree is 0
height( t(_,L,R), H ) :- % Height of binary tree t(_,L,R) is H if...
height(L, LH), % LH is the height of subtree L, and
height(R, RH), % RH is the height of subtree H, and
( LH > RH % if LH > RH, then
-> H is LH + 1 % H is LH + 1
; H is RH + 1 % otherwise, H is RH + 1
).
Or more directly, you can use the max
function available in Prolog (as @false points out):
height( nil, 0 ). % Height of nil tree is 0
height( t(_,L,R), H ) :- % Height of binary tree t(_,L,R) is H if...
height(L, LH), % LH is the height of subtree L, and
height(R, RH), % RH is the height of subtree H, and
H is max(LH, RH) + 1.
Again, note here that an expression on the right hand side of the is
will be evaluated by Prolog.
>
and>=
expect arithmetic expressions only. That should produce a clean error. AndH-1
is a term and not an expression... – false