Reputation: 88
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?
Upvotes: 1
Views: 119
Reputation:
It is the A=X-1
, and later the Y=X*Z
. The great thing about the Prolog top level is that you can easily try out what your code does:
?- A = X-1.
A = X-1.
?- A = 5-1.
A = 5-1.
Apparently, Prolog is mocking us :). The =
operator is used for unification; if you want to do arithmetic, you must use 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?
Upvotes: 2