I\'m trying to create a program in Prolog which takes two numbers - A and B and finds the sum of the numbers from A to B, including them.
To sum up: sum(1, 5, C) should
You can't instantiate C1
as C+A
because C
is not yet an integer.
Let's call sum(1, 5, C)
sum(1, 5, C)
---> 1 =< 5 ... true
---> A1 is 1 + 1 ... A1 = 2 (fine)
---> C1 is C + 2, C = something like _G232, not yet instantiated.
Let's take a look at your logic.
We would have a base case, when A and B are equal, that will be our 'starting' sum
sum(X,X,X).
Then we have our general case. each recursive call will give us the sum from k + 1 to n where we call sum(k,n,sum).
sum(A, B, C):- A =< B, A1 is A + 1, sum(A1,B,C1), C is C1 + A.