Prolog: find out if the sum of all elements of the list N is equal

I want to check if all values ​​are added to the list to a certain value. So far I have written the following:

list_sum([Head|Tail], Sum) :-
    list_sum(Tail, Sum1),
    Sum is Head + Sum1.

However, when trying, list_sum([1,2,3,4], 10)Prolog returns false. Can anyone help me out? I do not know what I am doing wrong.

+4
source share
2 answers

Use !

<Preview>: use_module ( library (clpfd) ).

To calculate the sum of a list of integers, simply use the sum/3 :

< > ? - ([1,2,3,4], # =, S). % Q: 1 + 2 + 3 + 4? S = 10.% A: 10 ? - sum ([1,2,3,4], # =, 10). % Q: 1 + 2 + 3 + 4 10? . % A: , ? - sum ([1,2,3,4], # =, 11). % Q: 1 + 2 + 3 + 4 11? . % A: ,

, clpfd (is)/2, @CapelliC:

< > ? - [A, B, C] ins 1.sup, sum ([A, B, C, A], # =, 12), ([], [A, B, ]).  A = B, B = 1, C = 9 ; A = 1, B = 2, C = 8 ; A = 1, B = 3, C = 7 ; A = 1, B = 4, C = 6 ; A = 1, B = C, C = 5 ; A = 1, B = 6, C = 4 ; A = 1, B = 7, C = 3 ; A = 1, B = 8, C = 2 ; A = C, B = 9, C = 1 ; A = 2, B = 1, C = 7 ; A = B, B = 2, C = 6 ; A = 2, B = 3, C = 5 ; A = 2, B = C, C = 4 ; A = 2, B = 5, C = 3 ; A = C, B = 6, C = 2 ; A = 2, B = 7, C = 1 ; A = 3, B = 1, C = 5 ; A = 3, B = 2, C = 4 ; A = B, B = C, C = 3 ; A = 3, B = 4, C = 2 ; A = 3, B = 5, C = 1 ; A = 4, B = 1, C = 3 ; A = 4, B = C, C = 2 ; A = 4, B = 3, C = 1 ; A = 5, B = C, C = 1.
+2

, .

Try the following:

list_sum([], 0).
list_sum([Head|Tail], Sum):-
    list_sum(Tail, Sum1),
    Sum is Head + Sum1.
+1
source

Source: https://habr.com/ru/post/1584595/


All Articles