prolog 需要计算树的大小 [英] prolog need to compute the tree size
本文介绍了prolog 需要计算树的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用以下方法获取树的大小:size(Tree,Size)
I need to get the size of a tree using: size(Tree,Size)
我目前的情况是错误的,请指教!
What I have so far is wrong, please advise!
size(empty, Size).
size(tree(L, _, R), Size) :-
size(L, Left_Size),
size(R, Right_Size),
Size is
Left_Size + Right_Size + 1.
输出应该产生:
?- size(node(1,2),X).
X = 2.
?- size(node(1,[2,3,4]),X).
X = 2.
?- size(node(node(a,b),[2,3,4]),X).
X = 3.
推荐答案
Prolog 是一种声明式语言,您必须正确地说明您的模式:
Prolog is a declarative language, you must state correctly your patterns:
size(node(L,R), Size) :- ... % why you add 1 to left+right sizes ?
从示例中,当看到任何不是节点的东西时,我建议停止使用 Size = 1 的递归:
From the samples, I suggest to stop the recursion with Size = 1 when anything that is not a node is seen:
size(node(L,R), Size) :- !, ...
size(_, 1).
这篇关于prolog 需要计算树的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文