Prolog 谓词 - 无限循环 [英] Prolog predicate - infinite loop

查看:16
本文介绍了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 谓词 - 无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆