I have two functions which return lists of results of the same size and I'm trying to check if results are the same. Order in lists can be different. I'm currently using the following function:
lists_are_the_same(List1, List2) ->
List1 -- List2 =:= [].
This function subtracts one list from the other and checks if the result is empty list. The problem is, such method is very slow and in my case lists can be fairly big.
Is there a faster way to check if two lists consist of exactly the same elements?
A faster way is sorting each list and then compare them as follows:
lists_are_the_same(List1, List2) ->
lists:sort(List1) =:= lists:sort(List2).
Based on the comment of Steve, it is important to know that all values in Erlang are sortable and have defined order, so it works for all possible list elements.
In case all your elements are unique you might want to use ordsets
instead of lists
. You can see also the documentation about using A -- B
operation:
The complexity of
lists:subtract(A, B)
is proportional tolength(A)*length(B)
, meaning that it is very slow if bothA
andB
are long lists. (If both lists are long, it is a much better choice to use ordered lists andordsets:subtract/2
.
Then you can check if they are equal via:
ordsets:is_subset(List1,List2) andalso ordsets:is_subset(List2,List1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With