'Step List With 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.



Solution 1:[1]

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

Solution 2:[2]

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adam Millerchip
Solution 2 Nicholas