定义关系`subsum(Set,Sum,Subset)`

Define the relation `subsum(Set,Sum,Subset)`

我有问题。

Define the relation subsum(Set,Sum,Subset) such that Set is a multiset of numbers expressed using lists, Subset is a subset of Set, and Sum is the union of the elements of Subset. The following results are obtained.

?- subsum([1,2,5,3,2],5,Sub).
Sub = [1, 2, 2] ;
Sub = [2, 3] ;
Sub = [5] ;
Sub = [3, 2] ;
false.
?-

The answers must not use any relationship other than the answer.

我的回答是:

subsum([], 0 ,[]).
subsum([_ | Xs], Sum, Ys) :- subsum(Xs, Sum, Ys).
subsum([X | Xs], Sum, [X | Ys]) :- subsum(Xs, Sum - X, Ys).

但是这段代码并没有像我预期的那样工作。 你能给我一些提示吗?

Could you give me some hints?

追踪代码;例如来自 SWISH:

你的第一行是 subsum([], 0 ,[]). ,它只能在所需总和为 0 时匹配,但如果没有元素总和等于目标,则不会有 0 在调用的时候在中间。


subsum(Xs, Sum - X, Ys) 运行 这个:

Sum = 5,
Y = 2,
writeln(Sum - Y)

你希望它写什么?它实际上写了什么?