Andres
Return true if a list has duplicates otherwise false
Hello.
I’m trying to check if a list has duplicates.
I didn’t have problems doing it with length and size:
def duplicate(list) do
a = length(list)
b = MapSet.size(MapSet.new(list))
a !== b
end
I also did it with Enum and pattern matching but I’m pretty sure there is a better way:
defmodule Checker do
def check(x) when is_boolean(x), do: x
def check(x), do: false
end
def main(list) do
list
|> Enum.reduce_while(%MapSet{}, fn x, acc ->
if x not in acc, do: {:cont, MapSet.put(acc, x)}, else: {:halt, true}
end)
|> Checker.check()
end
Could you help me to improve the last implementation in a more idiomatic way?
Thanks.
Marked As Solved
alexiss
Agree, I miss it. The final proposal whould be:
def has_duplicates?(list) do
list
|> Enum.reduce_while(%MapSet{}, fn x, acc ->
if MapSet.member?(acc, x), do: {:halt, false}, else: {:cont, MapSet.put(acc, x)}
end)
|> is_boolean()
end
Also Liked
peerreynders
Alternately shamelessly repurposing the implementation (uniq_list/3) of Enum.uniq/1:
defmodule Demo do
def duplicates?(list),
do: duplicates?(list, %{})
defp duplicates?([], _) do
false
end
defp duplicates?([head|tail], set) do
case set do
%{^head => true} ->
true
_ ->
duplicates?(tail, Map.put(set, head, true))
end
end
def run(list) do
list
|> duplicates?()
|> inspect()
|> IO.puts()
end
end
list = [1, 2, 3, 3, 2, 1]
uniq_list = Enum.uniq(list)
Demo.run(list) # true
Demo.run(uniq_list) # false
A lot can be learned by scouring through Elixir’s source code. The important thing is to understand how it works.
NobbZ
But reducing and finding the elements in a list again results in a runtime of O(n log n), using a MapSet is O(n).
l00ker
Last Post!
silverdr
Alternatively (ab)using (instead of repurposing) the implementation of Enum.uniq/1
!Enum.empty?(list -- Enum.uniq(list))
?
Probably wouldn’t use it for huuge lists though ![]()
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









