Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

elixir

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 
like image 701
ewH Avatar asked Apr 05 '16 15:04

ewH


People also ask

How do I access list elements in Elixir?

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.

Is Elixir a list?

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.

How do I print a list in Elixir?

Just throw in |> IO. inspect(label: "foo") anywhere to print the value with a label without affecting the behavior of the original code.

How do you find the length of a list in Elixir?

The length() function returns the length of the list that is passed as a parameter.


2 Answers

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"] 
like image 149
Gazler Avatar answered Sep 28 '22 05:09

Gazler


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.

like image 29
ewH Avatar answered Sep 28 '22 06:09

ewH