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

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -