Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a sum of sequence of numbers in Prolog

Tags:

loops

prolog

The task is to calculate a sum of natural numbers from 0 to M. I wrote the following code using SWI-Prolog:

my_sum(From, To, _) :- From > To, !.
my_sum(From, To, S) :-
  From = 0,
  Next is 1,
  S is 1,
  my_sum(Next, To, S).
my_sum(From, To, S) :-
  From > 0,
  Next is From + 1,
  S is S + Next,
  my_sum(Next, To, S).

But when I try to calculate:

my_sum(0,10,S), writeln(S).

I got False instead of correct number. What is going wrong with this example?

like image 982
Andrej Kirejeŭ Avatar asked Dec 04 '25 03:12

Andrej Kirejeŭ


1 Answers

this is surely false for Next \= 0: S is S + Next. Another more fundamental problem is that you're doing the computation in 'reverse' order. That is, when From > To and the program stop, you don't 'get back' the result. Then you should add an accumulator (another parameter, to be propagated to all recursive calls) and unify it with the partial sum at that last step...

Anyway, should be simpler:

my_sum(From, To, S) :-
  From < To,
  Next is From + 1,
  my_sum(Next, To, T),
  S is T + From.
my_sum(N, N, N).

| ?- my_sum(2, 4, N).
N = 9
like image 52
CapelliC Avatar answered Dec 07 '25 05:12

CapelliC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!