9

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,641
  • 1
  • 26
  • 43

1 Answers1

26

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,758
  • 2
  • 45
  • 56