抱歉,我认为leaf/1、node1/2、node2/3、node3/4 解决方案不是一个好的解决方案。
开发maxTree/2 很简单,但是...
treeMax(leaf(M), M).
treeMax(node1(V0, N1), M) :-
treeMax(N1, V1),
M is max(V0, V1).
treeMax(node2(V0, N1, N2), M) :-
treeMax(N1, V1),
treeMax(N2, V2),
M is max(V0, max(V1, V2)).
treeMax(node3(V0, N1, N2, N3), M) :-
treeMax(N1, V1),
treeMax(N2, V2),
treeMax(N3, V3),
M is max(V0, max(V1, max(V2, V3))).
...但是,如您所见,对于node4/5,您必须开发另一个treeMax 子句,另一个用于node5/6,另一个用于node6/7,usw。
建议:保持节点和叶子之间的区别,但对于节点,只实现一个带有值的结构体和一个子节点列表
所以你对子节点的数量没有限制;所以您的maxTree/2 不需要与更多子树的附加子句集成。
所以你的例子变成了
node(1, [leaf(1), node(9, [leaf(9), leaf(10), leaf(11)])])
和maxTree/2 变成
treeMax(leaf(M), M).
treeMax(node(V0, LN), M) :-
treeMax(LN, V1),
M is max(V0, V1).
treeMax([N], M) :-
treeMax(N, M).
treeMax([Nh | Nt], M) :-
treeMax(Nh, V0),
treeMax(Nt, V1),
M is max(V0, V1).
--- 编辑---
抱歉:我现在看到您的“不使用 'is' 谓词”。
这是一个奇怪的要求,但可以做到。
你的解决方案很痛苦(leaf/1,node1/2,node2/3,node3/4);我之前的解决方案变成了
treeMax(leaf(M), M).
treeMax(node1(V0, N1), V0) :-
treeMax(N1, V1),
V1 =< V0.
treeMax(node1(V0, N1), V1) :-
treeMax(N1, V1),
V1 > V0.
treeMax(node2(V0, N1, N2), V0) :-
treeMax(N1, V1),
treeMax(N2, V2),
V1 =< V0,
V2 =< V0.
treeMax(node2(V0, N1, N2), V1) :-
treeMax(N1, V1),
treeMax(N2, V2),
V1 > V0,
V2 =< V1.
treeMax(node2(V0, N1, N2), V2) :-
treeMax(N1, V1),
treeMax(N2, V2),
V2 > V0,
V2 > V1.
treeMax(node3(V0, N1, N2, N3), V0) :-
treeMax(N1, V1),
treeMax(N2, V2),
treeMax(N3, V3),
V1 =< V0,
V2 =< V0,
V3 =< V0.
treeMax(node3(V0, N1, N2, N3), V1) :-
treeMax(N1, V1),
treeMax(N2, V2),
treeMax(N3, V3),
V1 > V0,
V2 =< V1,
V3 =< V1.
treeMax(node3(V0, N1, N2, N3), V2) :-
treeMax(N1, V1),
treeMax(N2, V2),
treeMax(N3, V3),
V2 > V0,
V2 > V1,
V3 =< V2.
treeMax(node3(V0, N1, N2, N3), V3) :-
treeMax(N1, V1),
treeMax(N2, V2),
treeMax(N3, V3),
V3 > V0,
V3 > V1,
V3 > V2.
如您所见,leaf/1 需要一个 treeMax/2 子句,node1/2 需要两个子句,node2/3 需要三个子句,等等。
nodeN/N+1 需要 N+1 子句。
如果您使用基于单个 node/2 结构的解决方案,并带有子节点列表,那么我之前的解决方案将变为
treeMax(leaf(M), M).
treeMax(node(V0, LN), V0) :-
treeMax(LN, V1),
V1 =< V0.
treeMax(node(V0, LN), V1) :-
treeMax(LN, V1),
V1 > V0.
treeMax([N], M) :-
treeMax(N, M).
treeMax([Nh | Nt], V0) :-
treeMax(Nh, V0),
treeMax(Nt, V1),
V1 =< V0.
treeMax([Nh | Nt], V1) :-
treeMax(Nh, V0),
treeMax(Nt, V1),
V1 > V0.