How to determine if a list contains duplicates?

I want to know if a list contains any value more than once. Here is what I have.

has_dupes(List) -> has_dupes(List, []). has_dupes([Item|List], Seen) -> case lists:filter(fun(Elem) -> Elem == Item end, Seen) of [] -> has_dupes(List, [Item|Seen]); _ -> true end; has_dupes([], _Seen) -> false. 

Is there an easier / more concise / more idiomatic way to do this? I am new to Erlang.

+4
source share
3 answers
 erlang:length(List) == sets:size(sets:from_list(List)). 
+11
source

How about this possible solution?

 has_dupes([H|T]) -> case lists:member(H, T) of true -> true; false -> has_dupes(T) end; has_dupes([]) -> false. 
+4
source

Has 2 million lists of items to check. Release these two versions for speed. Usort seems to win, 6 seconds versus 316 seconds.

 14> timer:tc(fun() -> erlang:length(X) == erlang:length(lists:usort(X)) end). {6825493,false} 15> timer:tc(fun() -> erlang:length(X) == sets:size(sets:from_list(X)) end). {316297882,false} 
+1
source

All Articles