序言中的尾递归和、幂、gcd?
我怎样才能做到这一点:
为以下每个谓词给出尾递归定义。功率(X,Y,Z)
:XY=Z。gcd(X,Y,Z)
:X和Y的最大公约数是Z。sum(L,Sum)
:Sum 是 L 中元素的总和。
到目前为止,我已经这样做了,但不确定这是否正确
power(_,0,1) :- !.
power(X,Y,Z) :- Y1 is Y - 1,power(X,Y1,Z1),Z is X * Z1.
sum(void,0).
sum(t(V,L,R),S) :- sum(L,S1),sum(R,S2), S is V + S1 + S2.
how can I accomplish this:
Give a tail-recursive definition for each of the following predicates.power(X,Y,Z)
: XY=Z.gcd(X,Y,Z)
: The greatest common divisor of X and Y is Z.sum(L,Sum)
: Sum is the sum of the elements in L.
so far I have done this but not sure if that's correct
power(_,0,1) :- !.
power(X,Y,Z) :- Y1 is Y - 1,power(X,Y1,Z1),Z is X * Z1.
sum(void,0).
sum(t(V,L,R),S) :- sum(L,S1),sum(R,S2), S is V + S1 + S2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这些不是尾递归。您可以使用累加器编写尾递归变体,请参阅
你的总和在一棵树上,这是不寻常的,通常人们会使用列表。在 Prolog 中,[] 是空列表,[X|R] 是具有头部 X 和尾部 R 的非空列表的模式。
These are not tail recursive. You can write tail recursive variants by using an accumulator, see this answer.
Your sum is over a tree, which is unusual, normally one would use a list. In Prolog [] is the empty list and [X|R] is the pattern for a nonempty list with the head X and the tail R.