I can declare a range as follows:
range = 1..10
Is there a way to convert the range to a list?
In Elixir and Erlang we use `list ++ [elem]` to append elements.
The head is the first element of a list and the tail is the remainder of a list. They can be retrieved with the functions hd and tl. Let us assign a list to a variable and retrieve its head and tail.
The length() function returns the length of the list that is passed as a parameter.
Enum.to_list/1
is what you're looking for:
iex(3)> Enum.to_list 1..10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The generic way to convert an enumerable into a specific collectable is Enum.into
:
Enum.into 1..10, []
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You can also pass a transformation function as third argument:
Enum.into 1..10, %{}, &({&1, &1})
#=> %{1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 10}
Use Enum.map/2
range = 1..10
Enum.map(range, fn(x) -> x end)
or
Enum.map(range, &(&1))
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