In Elixir, you can return a list by using the square brackets [ ]. Simply enclose the elements you want in the list inside the square brackets and return it. For example, you can define and return a list of numbers like [1, 2, 3, 4, 5]. Lists are one of the basic data structures in Elixir and are commonly used to store multiple elements of the same type.
How do you check if a value is in a list in Elixir?
You can use the Enum.member?/2
function to check if a value is present in a list in Elixir. Here's an example:
1 2 3 4 5 6 7 8 |
list = [1, 2, 3, 4, 5] value = 3 if Enum.member?(list, value) do IO.puts("#{value} is in the list") else IO.puts("#{value} is not in the list") end |
In this example, we have a list [1, 2, 3, 4, 5]
and we want to check if the value 3
is present in the list. The Enum.member?/2
function returns true
if the value is in the list, and false
otherwise.
How to filter a list in Elixir?
To filter a list in Elixir, you can use the Enum.filter/2
function. This function takes a list and a predicate function as arguments, and it returns a new list containing only the elements for which the predicate function returns true.
Here's an example of how you can filter a list in Elixir:
1 2 3 4 5 |
list = [1, 2, 3, 4, 5] filtered_list = Enum.filter(list, fn(x) -> x > 2 end) IO.inspect(filtered_list) # output: [3, 4, 5] |
In this example, we have a list containing the numbers 1 to 5, and we use Enum.filter
to filter out only the elements that are greater than 2. The resulting filtered list is then stored in the filtered_list
variable and printed out.
What is the zip function in Elixir lists?
The zip function in Elixir lists takes two lists and merges them into a list of tuples where each tuple contains corresponding elements from the two input lists. If one of the input lists is shorter than the other, the resulting list will only include elements up to the length of the shortest list. It is similar to the zip function in other programming languages like Python.