recursion - Sum numbers up to N-M in Prolog -
hey need create function countnm(n,m,s) sums numbers n-m (and returns 0 if n equal or less m). have worked out , have makes sense when work through in head, uninstantiated...
sumnm(0,0,0). sumnm(n,m,s):- n=<m, s 0. sumnm(n,m,s):- n>m, n-m, b s+a, c m+1, sumnm(n,c,b).
the problem on line
b s+a,
at point, s
not bound, causing arithmetic look fail.
other that, logic behind look wrong. you're saying sum of 1 fewer number (b) equal total sum (s) plus current number (a). should other way around.
you can replace lastly predicate code:
sumnm(n,m,s):- n>m, n-m, c m+1, sumnm(n,c,b), s b+a.
here first calculate sum b, after add together it, resulting in total sum s.
recursion prolog
No comments:
Post a Comment