Prolog define the isEqual predicate so that isEqualXY says t

Prolog: define the isEqual predicate so that isEqual(X,Y) says that sets X and Y are equal. Two sets are equal if they have exactly the same elements, regardless of the order in which those elements are represented in the set.

Solution

Following is the solution which checks if two lists are equal irrespective of the order of the elements:

areq([],[]).*
areq([],[_|_]).
areq([Head1|Ta1], L):- member(Head1, L), areq(Ta1, L).

(This is to check if the elements in the list existed)

areq([],[]).
areq([],[_|_]).
areq([Head1|Ta1], L):- member(Head1, L), areq(Ta1, L), append([Head1], Ta1, U), areq(U, L).

This is used to sort elements and to ensure that neither list contained duplicate elements:

equal_elements(Lt1, Lt2) :-
sort(Lt1, Srtd1),
sort(Lt2, Srtd2),
Srtd1 == Srtd2.
Let us consider few sample queries:

| ?- equal_elements([2,3,4],[2,3,4,5]).
no

| ?- equal_elements([2,3,4],[4,2,3]).
yes

| ?- equal_elements([b(X),b(Y),b(Z)],[b(2),b(3),b(4)]).
no

| ?- equal_elements([b(X),b(Y),b(Z)],[b(Z),b(X),b(Y)]).


?- [user].


equal_elementsB([], []).
equal_elementsB([X|Xm], Ym) :-
selectd(X, Ym, Zm),
equal_elementsB(Xm, Zm).

Practically after execution, the following is the result we obtain:

?- equal_elementsB([2,3,4],[4,3,2]).
true. % succeeds

?- equal_elementsB([2,3,4],[A,B,C]), C=4,B=3,A=2.
A = 2, B = 3, C = 4 ; % logically correct
false.
However, the following code can also be used to check if two lists are equal:

is_equal([],[]).
is_equal([Head1|Tail1],[Head2|Tail2]):- Head1=:=Head2,is_equal(Tail1,Tail2).

Prolog: define the isEqual predicate so that isEqual(X,Y) says that sets X and Y are equal. Two sets are equal if they have exactly the same elements, regardles

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site