Make sure the two lists are made up of the same items.

I have two functions that return lists of results of the same size, and I'm trying to check if the results match. The order in the listings may be different. I am currently using the following function:

lists_are_the_same(List1, List2) -> List1 -- List2 =:= []. 

This function subtracts one list from another and checks if the result is empty. The problem is that such a method is very slow, and in my case the lists can be quite large.

Is there a faster way to check if two lists consist of the same elements?

+5
source share
2 answers

The faster way sorts each list and then compares them as follows:

 lists_are_the_same(List1, List2) -> lists:sort(List1) =:= lists:sort(List2). 

Based on Steve's comment, it’s important to know that all values ​​in Erlang are sortable and have a specific order , so it works for all possible list items.

+6
source

If all of your items are unique , you can use ordsets instead of lists . You can also see the documentation about using operation A -- B :

The complexity of lists:subtract(A, B) proportional to length(A)*length(B) , which means that it is very slow if both A and B are equal long lists. (If both lists are long, it is a much better choice to use ordered lists and ordsets:subtract/2 .

Then you can check if they are equal in:

 ordsets:is_subset(List1,List2) andalso ordsets:is_subset(List2,List1) 
+2
source

All Articles