Reputation: 2683
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
Upvotes: 111
Views: 104526
Reputation: 307
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
Upvotes: 2
Reputation: 84140
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"]
Upvotes: 172
Reputation: 53
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]))
Upvotes: 2
Reputation: 1220
Or just use in
:
iex(1)> "foo" in ["foo", "bar"]
true
iex(2)> "foo" in Tuple.to_list({"foo", "bar"})
true
Upvotes: 38
Reputation: 2683
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.
Upvotes: 63