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
You can either do [head | tail]. = list (If you need the first element, head, as well) or tail = tl(list) (if you don't need the head) to get the tail of a list, then just map over that.
Lists are a basic data type in Elixir for holding a collection of values. Lists are immutable, meaning they cannot be modified. Any operation that changes a list returns a new list. Lists implement the Enumerable protocol, which allows the use of Enum and Stream module functions.
Just throw in |> IO. inspect(label: "foo") anywhere to print the value with a label without affecting the behavior of the original code.
The length() function returns the length of the list that is passed as a parameter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With