Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get duplicates in a list in elixir?

If you want to get duplicates instead of uniq values in a list, how would you do this in a quick, dense script that uses pattern matching?

For example, with an input of ["ash", "bob", "cat", "bob", "ash"] how could I get ["ash", "bob"] ?

like image 267
Laser Avatar asked Sep 18 '25 14:09

Laser


2 Answers

Since you specified you wanted a quick, dense script, I think you should consider this solution:

l = ["ash", "bob", "cat", "bob", "ash", "ash"]

# to get all duplicates
l -- Enum.uniq(l) # => ["bob", "ash", "ash"]

# to get a unique list of duplicates
Enum.uniq(l -- Enum.uniq(l)) # => ["bob", "ash"]
like image 176
Paweł Obrok Avatar answered Sep 20 '25 05:09

Paweł Obrok


Here is how I would do it:

["ash", "bob", "cat", "bob", "ash"]
|> (&((&1 -- (&1 |> Enum.uniq())) |> Enum.uniq())).()

This is the same as doing:

my_list = ["ash", "bob", "cat", "bob", "ash"]
(my_list -- (my_list |> Enum.uniq())) |> Enum.uniq()

What is happening:

  1. get a list of all the unique values (the complement to what we want): my_list |> Enum.uniq()
  2. Use list subtraction to get the complement of these unique values.
  3. Use another call to Enum.uniq to get these "duplicates" in unique list.
like image 23
Peaceful James Avatar answered Sep 20 '25 04:09

Peaceful James