What kind of ruby ​​and operator in Elixir?

:

list1 = [1,2,3,4,5]  
list2 = [2,3,6]  
list1 & list2 = [2,3]

I need to find a list of repetitions, i.e. common elements in list1and list2.

+4
source share
2 answers

The function you are looking for is Set.intersection / 2 :

iex> Set.intersection(Enum.into([1, 2, 3 ,4 ,5], HashSet.new), Enum.into([2, 3, 6], HashSet.new))
[2, 3]

Note that converting to a set means that duplicates are not allowed:

Enum.into([1, 2, 3 ,2 ,5, 3], HashSet.new)
HashSet<[2, 3, 1, 5]>

Also note that the order is not supported:

iex>Enum.into([1, 2, 3 ,4 ,5, 6], HashSet.new) |> Set.to_list
[2, 6, 3, 4, 1, 5]
+5
source

Not sure if elixir has a similar operator &for lists.

But you can achieve your greedy result with the operator --twice:

iex> list1
# => [1, 2, 3, 4, 5]
iex> list2
# => [2, 3, 6]
iex> list3 = list1 -- list2
# => [1, 4, 5]   
iex> final_list = list1 -- list3
# => [2, 3] # this is your desired result

You can do this in one line:

iex> list1 -- (list1 -- list2)
# => [2, 3]
+4
source

Source: https://habr.com/ru/post/1613109/


All Articles