Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Step List With Elixir

Tags:

elixir

Can someone please provide a suggestion on how to iterate a list BUT with a batch of x at a time?

For example:

If the functionality existed:

["1","2","3","4","5","6","7","8","9","10"].step(5)|> IO.puts

Would produce in two iterations:

12345

678910

I believe Stream.iterate/2 is the solution but my attempts to do so given an array are not proving profitable.

like image 741
Dane Balia Avatar asked May 20 '15 13:05

Dane Balia


2 Answers

Enum.chunk_every/2 (or Stream.chunk_every/2) will break a list down into sublists of x elements:

iex> [1,2,3,4,5,6,7,8,9,10] |> Enum.chunk_every(5)                   
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

You can then act on each list, for example:

iex> ["1","2","3","4","5","6","7","8","9","10"]
     |> Enum.chunk_every(5)
     |> Enum.each(fn x -> IO.puts x end)
12345
678910
like image 82
Gazler Avatar answered Sep 19 '22 15:09

Gazler


Both Enum.chunk/2 and Enum.chunk/2 are deprecated.

Use Enum.chunk_every/2 and Stream.chunk_every/2 instead

like image 37
Nicholas Avatar answered Sep 21 '22 15:09

Nicholas