How to check if an item exists in an Elixir list or tuple?

It would seem simple, but I can not find it in the documents. I just need to return true or false if the item exists in a list or tuple. Is Enum.find/3 best way to do this?

 Enum.find(["foo", "bar"], &(&1 == "foo")) != nil 
+42
elixir
Apr 05 '16 at 15:35
source share
5 answers

Can you use enum.member? / 2

 Enum.member?(["foo", "bar"], "foo") # true 

With a tuple, you first want to convert to a list using Tuple.to_list / 1

 Tuple.to_list({"foo", "bar"}) # ["foo", "bar"] 
+57
Apr 05 '16 at 15:36
source share

Based on the answers here and in Elixir Slack, there are several ways to check if an item exists in a list. For the answer from @Gazler:

 Enum.member?(["foo", "bar"], "foo") # true 

or simply

 "foo" in ["foo", "bar"] # true 

or

 Enum.any?(["foo", "bar"], &(&1 == "foo") # true 

or if you want to find and return an element instead of true or false

 Enum.find(["foo", "bar"], &(&1 == "foo") # "foo" 

If you want to check a tuple, you need to convert it to a list (credit @Gazler):

 Tuple.to_list({"foo", "bar"}) # ["foo", "bar"] 

But, as @CaptChrisD pointed out in the comments, this is an unusual need for a tuple, because it is usually interested in the exact position of an element in a tuple for pattern matching.

+19
Apr 05 '16 at 22:53 on
source share

Or just use in :

 iex(1)> "foo" in ["foo", "bar"] true iex(2)> "foo" in Tuple.to_list({"foo", "bar"}) true 
+8
Sep 16 '16 at 14:27
source share

You can also use find_value

 iex(1)> Enum.find_value(["foo", "bar"],false, fn(x)-> x=="foo" end) true iex(2)> Enum.find_value(["foo", "bar"],false, fn(x)-> x=="food" end) false 
+1
Oct 28 '17 at 13:18
source share

I started programming in Elixir yesterday, but I will try something that I have done a lot in JS, maybe it is useful when the list contains a lot of elements and you do not want to go through it all the time using Enum.member

 map_existence = Enum.reduce(list,%{}, &(Map.put(&2,&1,true))) map_existence[item_to_check] 

You can also get a crossroads with another list:

 Enum.filter(some_other_list,&(map_existence[&1])) 
0
Nov 12 '17 at 1:38 on
source share



All Articles