Reading: Webster Ch. 22
Define the prediate max(X, Y, Z) that takes numbers X and Y and unifies Z with the maximum of the two.
max(X, Y, Z) :-
(X >= Y, Z is X, !);
Z is Y.
Define the predicate subsetsum(L, Sum, SubL) that takes a list L of numbers and a number Sum and unifies SubL with a subsequence of L such that the sum of the numbers in SubL is Sum. For example:
?- subsetsum([1, 2, 5, 3, 2], 5, SubSet).
SubSet = [1,2,2] ;
SubSet = [2,3] ;
SubSet = [5] ;
SubSet = [3,2] ;
false.
Your predicate should assume that L and Sum are instantiated, and should succeed once for each subsequence of L and adds up to Sum.
sum([],0).
sum([Head | Rest], X) :-
sum(Rest,RestS),
X is Head + RestS.
/* Borrowed From queens.pl */
subseq([],[]).
subseq([Item | RestX], [Item| RestY]) :-
subseq(RestX, RestY).
subseq(X, [_| RestY]) :-
subseq(X, RestY).
subsetsum(L, Sum, SubL) :-
subseq(SubL, L),
sum(SubL, Total),
Total =:= Sum.