简体   繁体   English

Prolog错误:因果关系超出本地堆栈

[英]Prolog Error: Out of Local Stack in factorial

I'm trying to make a factorial code in prolog but am getting error of out of local stack, that is, it is stuck in infinite loop. 我正在尝试在序言中编写阶乘代码,但出现本地堆栈错误,即卡在无限循环中。 I can't understand how. 我不明白 Here is my code: 这是我的代码:

fact(0,1).
fact(1,1).

fact(X,Y):- X\==0, A=X-1, fact(A,Z), Y=X*Z.

Where am I going wrong? 我要去哪里错了?

It is the A=X-1 , and later the Y=X*Z . 它是A=X-1 ,后来是Y=X*Z The great thing about the Prolog top level is that you can easily try out what your code does: 关于Prolog顶层的妙处在于,您可以轻松地尝试代码的功能:

?- A = X-1.
A = X-1.

?- A = 5-1.
A = 5-1.

Apparently, Prolog is mocking us :). 显然,Prolog在嘲笑我们:)。 The = operator is used for unification; =运算符用于统一; if you want to do arithmetic, you must use is/2 : 如果要进行算术运算,则必须使用is/2

?- is(A, -(5, 1)).
A = 4.

usually written as: 通常写为:

?- A is 5-1.
A = 4.

This just to show you that an expression is a term, and is evaluates the term in its second argument: 这只是为了向您展示一个表达式是一个术语,并在其第二个参数中评估该术语:

?- Expr = X-1, X = 3, Result is Expr.
Expr = 3-1,
X = 3,
Result = 2.

To your definition for factorial: it should work if you fix the arithmetic. 按照您对阶乘的定义:如果修正算术,它应该可以工作。 Note that it would be cleaner if the condition for X at the beginning says X > 1 instead of X \\== 0 : what does your current program do for fact(1,F) , and how many answers do you get? 请注意,如果开头的X > 1的条件是X X > 1而不是X \\== 0 ,那会更干净:您当前的程序对fact(1,F)做了什么,会得到多少答案?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM