Generate a sequence of N natural numbers

In Ruby, this can be done using splat

[*1..5] # => [1, 2, 3, 4, 5] 

How can this be done in Elixir?

I know that I could use reduce , but maybe there is an easier way?

+6
source share
1 answer

Elixir has a Range just like Ruby. They implement the Enumerable protocol , so you do not need to convert them to lists in most cases. Ranges usually behave the same as lists:

 iex> [1, 2, 3, 4, 5] |> Enum.map(fn x -> x*x end) [1, 4, 9, 16, 25] iex> 1..5 |> Enum.map(fn x -> x*x end) [1, 4, 9, 16, 25] 

However, if you really need a list for any reason, you can do the conversion through Enum.to_list :

 iex> 1..5 |> Enum.to_list [1, 2, 3, 4, 5] 
+11
source

Source: https://habr.com/ru/post/986425/


All Articles