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 find that C is 1+2+3+4+5 = 15
This is my code, which is not working :(
sum(A, B, C) :- A =< B, A1 is A+1, C1 is C+A, sum(A1, B, C1).
And then I test it with sum(1, 5, C).
What I get is ERROR: is/2: Arguments are not sufficiently instantiated, but I can't really get what is the problem. :(
Could you please help me to understand why it's not working and how to fix it? Thank you very much in advance! :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With