Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a sequence of N natural numbers

Tags:

elixir

In Ruby it is possible to do so using a splat

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

How can this be done in Elixir?

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

like image 449
user2205259 Avatar asked May 02 '15 21:05

user2205259


People also ask

What is the sequence of natural numbers?

the sequence 1, 2, 3, 4, 5, . . . of all positive integers arranged in increasing order. The fact that this sequence is infinite was already perceived in the early stages of the development of mathematics. Each positive integer in this sequence is usually called a natural number.

How do you write n natural numbers?

A set of natural numbers is typically denoted by the symbol ℕ. For example: ℕ = {1, 2, 3, 4, 5, 6, 7…}

What is the generating function of the sequence of natural numbers?

H(z)=z(1−z)2.


1 Answers

Elixir has Ranges just like Ruby. They implement the Enumerable protocol, so you don't need to convert them to lists in most cases. Ranges will usually behave the same way 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 some reason, you can do the conversion via Enum.to_list:

iex> 1..5 |> Enum.to_list
[1, 2, 3, 4, 5]
like image 121
Patrick Oscity Avatar answered Oct 12 '22 13:10

Patrick Oscity