本文介绍了Prolog列出差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写序言中的程序,该程序将执行以下操作:

I'm trying to make program in prolog that will do something like this:

diffSet([a,b,c,d], [a,b,e,f], X).
X = [c,d,e,f]

我写了这个:

diffSet([], _, []).
diffSet([H|T1],Set,Z):- member(Set, H), !, diffSet(T1,Set,Z).
diffSet([H|T], Set, [H|Set2]):- diffSet(T,Set,Set2).

但是那样,我只能从第一个列表中获取元素.如何从第二个元素中提取元素?

But in that way I can only get elements from the first list. How can I extract the elements from the second one?

@edit:成员正在检查H是否在Set中

@edit:member is checking if H is in Set

member([H|_], H).
member([_|T], H):- member(T, H).

推荐答案

有一个内置可从列表中删除元素:

There is a builtin that remove elements from the list:

diffSet([], X, X).

diffSet([H|T1],Set,Z):-
 member(H, Set),       % NOTE: arguments swapped!
 !, delete(T1, H, T2), % avoid duplicates in first list
 delete(Set, H, Set2), % remove duplicates in second list
 diffSet(T2, Set2, Z).

diffSet([H|T], Set, [H|Set2]) :-
 diffSet(T,Set,Set2).

这篇关于Prolog列出差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 07:11