Re: Enum.repeat/2

29 views
Skip to first unread message
Message has been deleted

Wojtek Mach

unread,
Mar 29, 2019, 7:47:14 AM3/29/19
to elixir-lang-core
iex(1)> List.duplicate(:something, 5)
[:something, :something, :something, :something, :something]

:-)

Hi there,

I would like to know your opinion about an `Enum.repeat/2` function. In test, I notice often that I write:

Enum.map(1..5, fn(_) ->  :something end)
[:something, :something, :something, :something, :something]

or 

for (_ Enter code here... <- 1..5), do: :something
=> [:something, :something, :something, :something, :something]

As I am not interested in the value of the input, I think a `Enum.repeat/2` function would be more efficient:
Enum.repeat(5, fn -> :something end)
=> [:something, :something, :something, :something, :something]


I am aware that `Enum.times/2` is deprecated in the past in favour of ranges. I want to highlight that in that function, the value was passed to the function.


What is your take? Or perhaps I overlooked a function?

Hylke Alons

unread,
Mar 29, 2019, 7:48:54 AM3/29/19
to elixir-lang-core
Hah, this is great! thanks!

Ben Wilson

unread,
Mar 29, 2019, 8:57:58 AM3/29/19
to elixir-lang-core
You can sort of do this with `Stream.repeatedly(fn -> :something end) |> Enum.take(5)`. It's a little longer, although it reads rather nicely.
Reply all
Reply to author
Forward
0 new messages