Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a default initialized list of size n in Elixir [duplicate]

Tags:

erlang

elixir

Is there a Elixir or Erlang function that creates a list of size n, default initialized with a given value?

Examples of the functionality in other languages:

# Python
l = [0] * 5

# Ruby
l = Array.new(5, 0)

# => [0, 0, 0, 0, 0]
like image 233
Luca Fülbier Avatar asked Jan 13 '17 01:01

Luca Fülbier


People also ask

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.

How do I create a list in Erlang?

In Erlang, Lists are created by enclosing the values in square brackets.

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.


1 Answers

There's List.duplicate/2:

iex(1)> List.duplicate(:foo, 3)
[:foo, :foo, :foo]

If instead of a static value you want to initialise the list with results of some computation you can always use for comprehensions:

iex(2)> for _i <- 1..3, do: :erlang.timestamp()
[{1484, 271802, 581891}, {1484, 271802, 581900}, {1484, 271802, 581906}]
like image 173
nietaki Avatar answered Nov 10 '22 19:11

nietaki