Prolog: Find out if sum of all list elements equals N -
i want check if values in list add value. far, have written following:
list_sum([head|tail], sum) :- list_sum(tail, sum1), sum head + sum1.
however, when try list_sum([1,2,3,4], 10)
prolog returns false
. me out? don't know i'm doing wrong.
use clpfd!
:- use_module(library(clpfd)).
for calculating sum of list of integers use clpfd library predicate sum/3
:
?- sum([1,2,3,4], #=, s). % q: 1+2+3+4? s = 10. % a: sum 10 ?- sum([1,2,3,4], #=, 10). % q: 1+2+3+4 equal 10? true. % a: yes, ?- sum([1,2,3,4], #=, 11). % q: 1+2+3+4 equal 11? false. % a: no, doesn't
a use case showing benefits of using clpfd instead of (is)/2
, suggested @capellic:
?- [a,b,c] ins 1..sup, sum([a,b,c,a], #=, 12), labeling([], [a,b,c]). = b, b = 1, c = 9 ; = 1, b = 2, c = 8 ; = 1, b = 3, c = 7 ; = 1, b = 4, c = 6 ; = 1, b = c, c = 5 ; = 1, b = 6, c = 4 ; = 1, b = 7, c = 3 ; = 1, b = 8, c = 2 ; = c, b = 9, c = 1 ; = 2, b = 1, c = 7 ; = b, b = 2, c = 6 ; = 2, b = 3, c = 5 ; = 2, b = c, c = 4 ; = 2, b = 5, c = 3 ; = c, b = 6, c = 2 ; = 2, b = 7, c = 1 ; = 3, b = 1, c = 5 ; = 3, b = 2, c = 4 ; = b, b = c, c = 3 ; = 3, b = 4, c = 2 ; = 3, b = 5, c = 1 ; = 4, b = 1, c = 3 ; = 4, b = c, c = 2 ; = 4, b = 3, c = 1 ; = 5, b = c, c = 1.
Comments
Post a Comment