title: Prolog: check if two lists have the same elements
body: <p>I am new to Prolog and I am having a problems checking if two lists have exactly the same elements. It is possible for the elements to be in different orders. I have this code:</p>
  
  <pre><code>myremove(X, [X|T], T).   
  myremove(X, [H|T], [H|R]) :-
     myremove(X, T, R).
  
   same_elements([], []).
   same_elements([H1|T1], L2) :-      
      myremove(H1, L2, Nl2),  
      same_elements(T1, Nl2).
  </code></pre>
  
  <p>It works except that </p>
  
  <pre><code>?- same_elements([b,c,a], X).
  </code></pre>
  
  <p>causes an out of memory error after returning the first result. So then I tried to narrow down the result set by checking that the length of the lists are equal and checking that H1 is a member of L2:</p>
  
  <pre><code>mylength([], 0).
  mylength([_|T], R) :-
     mylength(T, Nr),
     R is Nr+1.
  
  mymember(X, [X|_]).
  mymember(X, [_|T]) :-
     mymember(X, T).
  
  same_elements([], []).
  same_elements([H1|T1], L2) :- 
     mylength([H1|T1], X),
     mylength(L2, Y),
     Y = X,
     mymember(H1, L2),
     myremove(H1, L2, Nl2),
     same_elements(T1, Nl2).
  </code></pre>
  
  <p>Now both</p>
  
  <pre><code>?- same_elements([b,c,a], X).
  ?- same_elements(X, [b,c,a]). 
  </code></pre>
  
  <p>return all of the results, but then they just hang at the end.  Is there a better way to do this? </p>