如何用impolog正确地编写暗示的含义?

问题描述:

我试图写一个谓词,当且仅然后如果列表d包含列表A元素,次数的部分是在列表A中。例如,这将是真实的 -如何用impolog正确地编写暗示的含义?

d [1 ,5,5,3]; A [4,6,1,0,5,3,5]

将为真

d [1,5,5,3]; A [4,6,1,0,5,3,5,5]

将是错误的,因为D有5次只有两次,但A有5次三次。我正在试图做到这一点。我的代码片段是fallows-

sub_third(_, []) :- 
    true. 

sub_third(D, [H|T]) :- 
    member(H, D) -> 
     select(H, D, D_new), sub_third(D_new, T) ; 
     false. 

third(_, [], _) :- 
    true. 

third(D, [H|T], A) :- 
    (\+member(H, D) -> 
     select(H, A, A_new), third(D, T, A_new) ; 
     third(D, T, A)) -> 
      (sub_third(D, A_new); 
      false). 

基本上我在做什么这里传递“第三”谓词列表d和两次名单A.有了第一个实现我试图从第二列表中删除所有的元素,在第一个A列表中找不到(如果H元素存在于列表D中,则用下一个T元素调用递归调用并且不作任何更改,但是如果在D列表中找不到H,则将其从第二个列表中移除并且再次调用递归,但修改了A列表)。当没有更多的T元素时,如果所有元素都是相同的计数,则列表A应该只包含与列表D相同的元素,然后使用子第三谓词查找。 Sub_third很好,所以我认为这个错误应该在影响范围内,因为我不熟悉它们。

P.S.成员函数检查元素是否是列表的成员,并且select函数接受元素和列表,然后从第一个列表中删除给定元素,从而创建第三个列表。 (这就是我在这里使用它的原因)

您应该尝试为谓词找到更清晰的名称。即使你知道sub_third应该是什么意思,我们也不知道。这使得更难理解和修改你的代码。

您使用select/3的基本想法很好,但您尚未正确分解问题。尝试首先计算您的列表之间的差异,然后检查它不包含任何不需要的元素的额外属性:

% list_subtract(Xs, Ys, Zs) is true if Zs is a list obtained by removing one 
% occurrence of each element of Ys from Zs. False if there are elements in 
% Ys that have no corresponding occurrence in Xs. 
list_subtract(Xs, [], Xs). 
list_subtract(Xs, [Y|Ys], Zs) :- 
    select(Y, Xs, Xs1), 
    list_subtract(Xs1, Ys, Zs). 

% tests 
:- list_subtract([4, 6, 1, 0, 5, 3, 5], [1, 5, 5, 3], Zs), Zs = [4, 6, 0]. 
:- list_subtract([4, 6, 1, 0, 5, 3, 5, 5], [1, 5, 5, 3], Zs), Zs = [4, 6, 0, 5]. 

% list_subtract_without_rest(Xs, Ys, Zs) is true if Ys can be subtracted 
% from Xs in the sense of the list_subtract/3 predicate, and the remaining 
% difference Zs does not contain any elements of Ys. 
list_subtract_without_rest(Xs, Ys, Zs) :- 
    list_subtract(Xs, Ys, Zs), 
    \+ (member(Z, Zs), member(Z, Ys)). 

% tests 
:- list_subtract_without_rest([4, 6, 1, 0, 5, 3, 5], [1, 5, 5, 3], _). 
:- \+ list_subtract_without_rest([4, 6, 1, 0, 5, 3, 5, 5], [1, 5, 5, 3], _). 
+0

谢谢!你能否也请查看我最近关于prolog的问题,因为现在还没有答案:/? http://*.com/questions/40766039/how-to-return-a-value-in-prolog – Oskars

+0

不客气!如果您对我的答案满意,请点击复选标记以正式“接受”答案。 –