Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program in Prolog for sum of numbers in interval

Tags:

prolog

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! :)

like image 625
Faery Avatar asked Jan 22 '26 09:01

Faery


1 Answers

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.
like image 178
C.B. Avatar answered Jan 24 '26 04:01

C.B.