I use ChatGPT quite a bit by asking - “How do I do this using Elixir?” The answers are usually pretty good. Here’s a question I just asked today along with the response:
My question:
Using Elixir, how do I check to see if two lists have the same members, regardless of the order?
ChatGPT said:
ChatGPT
In Elixir, you can check if two lists contain the same members, regardless of order, by sorting each list and comparing them. This approach works because sorting ensures both lists will have the same order if they contain the same elements.
Here’s a simple example:
def same_members?(list1, list2) do
Enum.sort(list1) == Enum.sort(list2)
end
Example Usage
same_members?([1, 2, 3], [3, 2, 1]) # returns true
same_members?([1, 2, 3], [3, 2, 2]) # returns false
This approach works well for lists with unique elements. However, if you have large lists and performance is a concern, you might consider using a different approach that doesn’t require sorting, such as converting the lists to maps of element counts and comparing those.
You said:
Are you sure there isn’t a built in function that does this check?
ChatGPT said:
ChatGPT
You’re right; Elixir actually has a built-in function for this exact purpose: Enum.frequencies/1
. By using it, you can create a frequency map for each list and then compare those maps directly, which is both efficient and concise.
Here’s how you can do it:
def same_members?(list1, list2) do
Enum.frequencies(list1) == Enum.frequencies(list2)
end
Example Usage
same_members?([1, 2, 3], [3, 2, 1]) # returns true
same_members?([1, 2, 3], [3, 2, 2]) # returns false
Using Enum.frequencies/1
is beneficial because it directly compares the counts of each unique element in each list, which avoids sorting and is faster for large lists.