Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the ruby & operator in Elixir?

Tags:

ruby

elixir

like this:

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

I need to find the repeat list i.e. common items in list1 and list2.

like image 320
Yingce Avatar asked Jan 07 '23 07:01

Yingce


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]

Please note that the conversion to a set means that duplicates are not permitted:

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

Also note that order is not maintained:

iex>Enum.into([1, 2, 3 ,4 ,5, 6], HashSet.new) |> Set.to_list
[2, 6, 3, 4, 1, 5]
like image 195
Gazler Avatar answered Feb 27 '23 02:02

Gazler


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

But, you can achive your desried result by using 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 it in one line too:

iex> list1 -- (list1 -- list2)
# => [2, 3]
like image 22
K M Rakibul Islam Avatar answered Feb 27 '23 01:02

K M Rakibul Islam