这是问题陈述:
给定一个整数列表 L 和一个整数 S,生成所有元素加起来为 S 的子列表。
这是我的解决方案:
domains
list=integer*
clist=list*
predicates
sum(list,integer)
check(clist,clist,integer)
gensub(list,list)
getsub(list,clist,integer)
clauses
%gets all possible subsets with gensub and findall, binds them to
%and then checks the subsets to see if the elements add up to S
%and adds the correct ones to Rez.
%Goal example: getsub([1,2,5,6],X,7)
getsub([], [], _).
getsub(L, Rez, S):-
findall(LR, gensub(L,LR), X),
check(X, Rez, S).
%generates all possible subsets of the given set
gensub([], []).
gensub([E|Tail], [E|NTail]):-
gensub(Tail, NTail).
gensub([_|Tail], NTail):-
gensub(Tail, NTail).
%checks if the sum of the elements of a list is S
sum([], S):-S=0.
sum([H|T], S):-
N=S-H,
sum(T, N).
%checks if each sublist of a given list of lists, has the sum of elements S
check([], [], S).
%the LR variable here gives a warning after entering the goal
check([H|T], [H|LR], S):-
sum(H, S).
因此,在我运行它并被要求输入目标之后,我尝试这样做getsub([1,2,5,6],X,7)
以获取其元素加起来为 7 的所有子集,但我得到一个No Solution
, 和 check 子句中变量的警告LR
,变量是不受约束。我不确定我做错了什么,或者是否有更简单的解决方案。任何帮助表示赞赏。