Trying to calculate the triangular number sequence in Prolog. This is my solution: where X is the nth position of the sequence and Y is the result.
triang(1, 1).
triang(X, Y) :-
X>0,
A is X - 1,
triang(A, B),
Y is B + X.
?- triang(5,X).
X = 15
But when i try to do for example triang(X,10) I receive an error
Arguments are not sufficiently instantiated.
I guess this is because X is not defined in the consult.
is there any recommendation how to solve this problem,thank you.
First of all, the result you got is not that bad. It says: sorry, I am unable to come to a conclusion and before producing an incorrect result, I prefer to produce an error.
The actual reason is the following goal
So here we ask for
Xthat are greater than zero. And there are many, in fact infinitely many. There is no direct way to enumerate that set for this built-in and thus it prefers the error.However, with
library(clpz)orclpfd, there is a better way:So now there is an answer to
#X #> 0. The answer is often called a constraint. In this case it tells us thatXmust be in the interval1up to (kind of) infinity.