Using the printlist/1 predicate in Prolog to sum up all numbers in a list -
i trying use printlist/1
predicate sum numbers in list kind of got stuck.... tried come code keep getting false
.
here i've come with:
printlist([]). printlist([h|t], totalsum) :- print (h+totalsum), nl, printlist(t, totalsum).
i know it's wrong , it's last part. appreciated!
i query way:
?- printlist([1,2,3]). false.
as paulo said, defining 2 predicates here, incorrect.
here solution:
printlist([], 0). printlist([h|t], sum) :- printlist(t, subsum), sum subsum + h.
sample query:
?- printlist([1,2,3,5], l). l = 11.
@ paulo requested), tail recursive version:
printlist(l, sum) :- sumac(l, 0, sum). sumac([], acc, acc). sumac([h|t], acc, sum) :- nacc acc + h, sumac(t, nacc, sum).
Comments
Post a Comment