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

Elixir

Elixir Problem Overview


This is seemingly simple, but I can't seem to find it in the docs. I need to simply return true or false if an item exists in a list or tuple. Is Enum.find/3 really the best way to do this?

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

Elixir Solutions


Solution 1 - Elixir

You can use Enum.member?/2

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

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

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

Solution 2 - Elixir

Based on the answers here and in Elixir Slack, there are multiple ways to check if an item exists in a list. Per answer by @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 the item instead of true or false

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

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

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

But as @CaptChrisD pointed out in the comments, this is an uncommon need for a tuple because one usually cares about the exact position of the item in a tuple for pattern matching.

Solution 3 - Elixir

Or just use in:

iex(1)> "foo" in ["foo", "bar"]
true
iex(2)> "foo" in Tuple.to_list({"foo", "bar"})
true

Solution 4 - Elixir

I started programming in Elixir yesterday, but I will try something I did a lot in JS, maybe it is useful when the list has a lot of elements and you don't want to traverse 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 retrieve an intersection with some other list:

Enum.filter(some_other_list,&(map_existence[&1]))

Solution 5 - Elixir

You can use Enum.find_value/3 too:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionewHView Question on Stackoverflow
Solution 1 - ElixirGazlerView Answer on Stackoverflow
Solution 2 - ElixirewHView Answer on Stackoverflow
Solution 3 - ElixirslashmiliView Answer on Stackoverflow
Solution 4 - ElixirJohel CarvalhoView Answer on Stackoverflow
Solution 5 - ElixirSabit HurairaView Answer on Stackoverflow