Hello can anyone help me compute the sum of the first n numbers. For example n=4 => sum = 10. So far I've wrote this
predicates
sum(integer,integer)
clauses
sum(0,0).
sum(N,R):-
N1=N-1,
sum(N1,R1),
R=R1+N.
This one works but I need another implementation. I don't have any ideas how I could make this differen . Please help
This is the "heart" of your program:
The
=/2predicate (note the/2means it accepts 2 arguments) is the instantiation predicate, not an assignment, or logical equal. It attempts to unify its arguments to make them the same. So ifNis anything but0, thenR=R+Nwill always fail becauseRcan never be the same asR+N. Likewise forN=N-1: it will always fail becauseNandN-1can never be the same.In the case of
=/2(unification), expressions are not evaluated. They are just terms. So ifY = 1, thenX = Y + 1unifiesXwith1+1as a term (equivalently written+(1,1)).Because of the above issues,
sumwill always fail.Numerical assignment of an arithmetic expression is done in Prolog with the
is/2predicate. Like this:This operator unifies the value of
Xto be the same as the value of the evaluated expressionY+1. In this case, you also cannot haveX is X+1for the same reason given above:Xcannot be made the same asX+1and Prolog does not allow "re-instantiation" of a variable inside of a clause. So you would need something like,X1 is X + 1. Also note that foris/2to work, everything in the expression on the right must be previously instantiated. If any variables in the expression on the right do not have a value, you will get an instantiation error or, in the case of Turbo Prolog, Free variable in expression....So you need to use different variables for expression results, and organize the code so that, if using
is/2, variables in the expression are instantiated.EDIT
I understand from Sergey Dymchenko that Turbo Prolog, unlike GNU or SWI, evaluates expressions for
=/2. So the=will work in the given problem. However, the error regarding instantiation (or "free variable") is still caused by the same issue I mentioned above.