Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Elixir, how can a range be converted to a list?

Tags:

elixir

I can declare a range as follows:

range = 1..10

Is there a way to convert the range to a list?

like image 949
epotter Avatar asked Sep 16 '14 19:09

epotter


People also ask

How do I add to my list in Elixir?

In Elixir and Erlang we use `list ++ [elem]` to append elements.

How do you get the first element of a list in Elixir?

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.

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.


3 Answers

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]
like image 58
Chris McCord Avatar answered Oct 15 '22 07:10

Chris McCord


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}
like image 17
Patrick Oscity Avatar answered Oct 15 '22 07:10

Patrick Oscity


Use Enum.map/2

range = 1..10
Enum.map(range, fn(x) -> x end)

or

Enum.map(range, &(&1))
like image 10
konole Avatar answered Oct 15 '22 08:10

konole