如何检查一个项目是否存在于长生不老药列表或元组?

这看起来很简单,但我在文件里找不到。如果一个项目存在于一个列表或元组中,我只需返回 truefalseEnum.find/3真的是最好的方法吗?

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

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"]

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.

Or just use in:

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

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

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]))