我做了一个谓词,它以2个列表作为参数,并返回一个与“recipesub”产品连接的列表,但是我需要制定第三个规则来禁止如果手头的产品是空白列表,则插入产品。序言:选择不在列表递归期间插入元素
所以第一个列表看起来是这样的:
recipe([ingredient(rice,4),ingredient(salt,3),ingredient(water,5)]).
,第二个是这样的:
ingredients([ingredient(rice,3),ingredient(salt,4),ingredient(water,4),
在它返回的那一刻:List = [ingredient(rice,1),[],ingredient(water,1)]
我希望它返回:List = [ingredient(rice,1),ingredient(water,1)]
need_to_buy([],_,List):- List = [].
need_to_buy([H|Hs],[X|Xs],[Difference|List]):-
H = ingredient(Type,Amount),
recipesub(Type,Amount,[X|Xs],Difference),
need_to_buy(Hs,[X|Xs],List).
以下是我用这个解决方案得到了多少。
/*need_to_buy([H|Hs],[X|Xs],List):-
H = ingredient(Type,Amount),
recipesub(Type,Amount,[X|Xs],Difference),
Difference = [],
need_to_buy(Hs,[X|Xs],List).*/
这是支持断言recipesub。
recipesub(Type,Amount,[],Difference):-
Difference = ingredient(Type,Amount).
recipesub(Type,Amount,[Z|_],Difference):-
Z = ingredient(Type,Stock),
Amount>Stock,
NewAmount is Amount-Stock,
Difference = ingredient(Type,NewAmount).
recipesub(Type,Amount,[Z|_],Difference):-
Z = ingredient(Type, Stock),
Stock >= Amount,
Difference = [].
recipesub(Type,Amount,[Z|Zs],Difference):-
Z = ingredient(WrongType,_),
WrongType \= Type,
recipesub(Type,Amount,Zs,Difference).
[MCVE](http://stackoverflow.com/help/mcve),请。这个'recipesub/4'是什么? – false 2014-11-04 13:59:55
Recipesub是一个谓词,它将第一个列表的头部与第二个列表中的每个元素进行递归比较,如果“H”中的变量“Amount”小于X中的“Amount”,则返回差值=成分(type,requiredAmount),但如果X中的变量Amount大于H中的变量Amount,则返回一个空列表。 – pinkyring 2014-11-04 14:12:08
好的,对不起,我现在已经尽了我的能力。 – pinkyring 2014-11-04 14:22:50