7

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]
Luca Fülbier
  • 2,451
  • 1
  • 22
  • 40

1 Answers1

22

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}]
nietaki
  • 8,227
  • 2
  • 43
  • 54