如何在prolog中找到列表中的差异并确定列表是否相同(相同的元素但不必具有相同的顺序) [英] How to find differences in lists in prolog and determine if the lists are the same (same elements but doesnt have to have the same order)
问题描述
如果我有两个列表,说 A 和 B 由不同的字母组成.列表 A 中的 [b,a,c] 和列表 B 中的 [b,d,c,e]我怎样才能让 prolog 给我 C,这是 A 没有包含在列表 B 中的元素列表前任.所以如果我输入
差异([b,a,c],[b,d,c,e],C).
我希望答案如下:C=[a]
如果我有两个列表,其中列表 A 由 [a,b,c] 组成,列表 B 是 [c,a,b]我希望结果是 Yes
如果我输入:same([a,b,c],[c,a,b]).
因为它们包含相同的元素,所以它们的顺序不同并不重要.此外,如果所有元素都相同,它应该只回答是,而不是 3/4 是正确的.
If i have two lists where list A is made up off [a,b,c] and list B is [c,a,b]
i want the result to be Yes
if i type:
same([a,b,c],[c,a,b]).
since they contain the same elements the fact that they are in a different order does not matter. Also it should only answer yes if all of the elements are the same not if 3/4 are right.
推荐答案
由于这看起来像作业,所以我只会给出一些想法,而不是实际代码:
Since this looks like homework I will give some thoughts only not actual code:
首先,您可以从确定元素是否为列表成员的成员过程开始:
First you can start with a member procedure that determines if an element is a member of a list:
member(X, [X|_]).
member(X, [_|T]) :- member(X, T).
所以 X 要么是列表的头部,要么是尾部的成员.
So X is either the head of the list or a member of the tail.
您的第一个问题可以这样回答:
Your first question can then be answered as:
1. If list A is empty then list C is empty
2. The head of A (HA) is the head of C if member(HA, B) is false AND the Tail of C (CT) can be found by recursively calling the procdure with the tail of A (TA), B and CT.
3. Otherwise, if HA is a member of B then just recusively call the procedure on TA, B and C
<小时>
同样,第二个问题可以使用上述程序来回答.如果 A 中不在 B 中的字母列表为空且 A 的每个元素都是 B 的成员,那么它们是相同的.
Similarly, the second question can be answered using the above procedure. If the list of letters in A that is not in B is empty AND each element of A is a member of B then they are the same.
我希望这会有所帮助.您可以随时发布您尝试过的内容,以便我们提供更多指导.
I hope this helps a little. You can always post what you tried so we can give more pointers.
这篇关于如何在prolog中找到列表中的差异并确定列表是否相同(相同的元素但不必具有相同的顺序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!