Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list in two equal halves (±1)

Tags:

elixir

I know I can split an even list in two equal halves in elixir by doing this:

list   = [1, 2, 3, 4, 5, 6]
len    = length(list)/2 |> round

[a, b] = Enum.chunk(list, len)            # => [[1, 2, 3], [4, 5, 6]]

but is there a ruby-esque method built-in or some more efficient way of doing this that also handles odd-length lists?

like image 480
Sheharyar Avatar asked Oct 09 '15 20:10

Sheharyar


1 Answers

Enum.chunk actually takes 4 arguments and will work with an odd length list if you include the 4th (pad) argument:

iex(14)> Enum.chunk([1,2,3,4,5], 3, 3, [])
[[1, 2, 3], [4, 5]]
like image 64
Gazler Avatar answered Oct 21 '22 16:10

Gazler