本文介绍了Prolog谓词-无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为自然数创建2的幂的Prolog谓词.自然数是:0,s(0),s(s(0))等等.

I need to create a Prolog predicate for power of 2, with the natural numbers.Natural numbers are: 0, s(0), s(s(0)) ans so on..

例如:

?- pow2(s(0),P).
P = s(s(0));
false.
?- pow2(P,s(s(0))).
P = s(0);
false.

这是我的代码:

times2(X,Y) :-
  add(X,X,Y).

pow2(0,s(0)).
pow2(s(N),Y) :-
  pow2(N,Z),
  times2(Z,Y).

它与第一个示例完美配合,但在第二个示例中进入了无限循环..
我该如何解决?

And it works perfectly with the first example, but enters an infinite loop in the second..
How can I fix this?

推荐答案

这是由于pow2的评估顺序而发生的.如果切换pow2的顺序,则第一个示例将陷入无限循环.因此,您可以先检查Y是var还是nonvar.

This happends because the of evaluation order of pow2.If you switch the order of pow2, you'll have the first example stuck in infinite loop..So you can check first if Y is a var or nonvar.

像这样:

times2(X,Y) :-
  add(X,X,Y).

pow2(0,s(0)).
pow2(s(N),Y) :-
  var(Y),
  pow2(N,Z),
  times2(Z,Y).
pow2(s(N),Y) :-
  nonvar(Y),
  times2(Z,Y),
  pow2(N,Z).

这篇关于Prolog谓词-无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 16:25
查看更多