height 不是返回高度的函数。当第二个参数是第一个参数的高度时,predicate 为真。所以你可以使用height(L,_) > height(R,_)。您必须执行height(L,LH), height(R,RH) 并将LH 与RH 进行比较。出于类似的原因,您无法查询height(L, H-1) 并获得预期结果,因为正如@false 指出的那样,H-1 在此上下文中是术语'-'(H,1),并且不被解释为算术表达式。在 Prolog 中,算术表达式仅在其位于 is 表达式的右侧或在算术比较表达式中时才会被解释。
因此,您更正的谓词如下所示:
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
).
或者更直接地,您可以使用 Prolog 中提供的max 函数(正如@false 指出的那样):
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.
再次注意,is 右侧的表达式将由 Prolog 求值。