简体   繁体   中英

What's the ruby & operator in Elixir?

like this:

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

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

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]

Not sure if elixir has a similar & operator for list s.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM