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]
The length() function returns the length of the list that is passed as a parameter.
In Erlang, Lists are created by enclosing the values in square brackets.
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.
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}]
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