Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog program to find equality of two lists in any order

I wanted to write a Prolog program to find equality of two lists, where the order of elements
doesn't matter. So I wrote the following:

del(_, [], []) .
del(X, [X|T], T).  
del(X, [H|T], [H|T1]) :-
   X \= H,
   del(X, T, T1).

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

equal([], []).  
equal([X], [X]).  
equal([H1|T], L2) :-
   member(H1, L2),
   del(H1, L2, L3),
   equal(T, L3).  

But when I give input like equal([1,2,3],X)., it doesn't show all possible values of X. Instead, the program hangs in the middle. What could be the reason?

like image 506
Happy Mittal Avatar asked Apr 26 '10 00:04

Happy Mittal


People also ask

How do you check if two lists are equal in prolog?

“prolog check if 2 lists have the same items” Code Answercommon_list([X],[X]). common_list([X|Tail],Y):- member(X,Y).

How do you find the tail of a list in prolog?

In Prolog list elements are enclosed by brackets and separated by commas. Another way to represent a list is to use the head/tail notation [H|T]. Here the head of the list, H, is separated from the tail of the list, T, by a vertical bar. The tail of a list is the original list with its first element removed.

How do you find the nth element in prolog?

match([Elem|Tail],Num,Num,Elem). match([Elem|Tail],Num,C,MatchedNumber):- match(Tail,Num,N,Elem), C is N+1. In the first line I say, if the requested element number is equal to counter, then give the first element of the current list to the variable called MatchedNumber .


1 Answers

isSubset([],_).
isSubset([H|T],Y):-
    member(H,Y),
    select(H,Y,Z),
    isSubset(T,Z).
equal(X,Y):-
    isSubset(X,Y),
    isSubset(Y,X).
like image 163
Mr. Berna Avatar answered Oct 05 '22 12:10

Mr. Berna