开发者

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)

  1. If i have two lists say A and B made upp of different letters. [b,a,c] in list A and [b,d,c,e] in list B how can i get prolog to give me C,which is a list of elements that A has which are not included in list B Ex. So if i type difference([b,a,c],[b,d,c,e],C). I want t开发者_如何学编程he answer to read: C=[a]

  2. 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).

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜