loops - How to calculate a sum of sequence of numbers in Prolog -


the task calculate sum of natural numbers 0 m. wrote following code using swi-prolog:

my_sum(from, to, _) :- > to, !. my_sum(from, to, s) :-   = 0,   next 1,   s 1,   my_sum(next, to, s). my_sum(from, to, s) :-   > 0,   next + 1,   s s + next,   my_sum(next, to, s). 

but when try calculate:

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

i got false instead of correct number. going wrong example?

this surely false next \= 0: s s + next. more fundamental problem you're doing computation in 'reverse' order. is, when from > to , program stop, don't 'get back' result. should add accumulator (another parameter, propagated recursive calls) , unify partial sum @ last step...

anyway, should simpler:

my_sum(from, to, s) :-   < to,   next + 1,   my_sum(next, to, t),   s t + from. my_sum(n, n, n).  | ?- my_sum(2, 4, n). n = 9 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -