rahul
#1
I am trying to partition a list of numbers into sub-lists of even and odd numbers using Enum.chunk_by/2.
iex> Enum.chunk_by([1,2,3,4,5,6], &(rem(&1, 2))
[[1], [2], [3], [4], [5], [6]]
I was expecting chunk_by to return two lists - [1,3,5], [2,4,6].
Can’t figure out whats wrong. Any pointers appreciated!
Cheers
Rahul
Hello and welcome to the forum…
using chunk_by will chunk each time the function change value, so the return is normal.
Maybe use Enum.split_with for what You want… like this
iex> Enum.split_with([1,2,3,4,5,6], &(rem(&1, 2)==0))
{[2, 4, 6], [1, 3, 5]}
# or like that...
iex> Enum.split_with([1,2,3,4,5,6], &(rem(&1, 2)==1))
{[1, 3, 5], [2, 4, 6]}
4 Likes
hauleth
#3
Chunk by group only consecutive values, not all. If you want to group all then use @kokolegorille example with Enum.split_with/2
.
1 Like
rahul
#4
Great, appreciate your help and explanation @kokolegorille @hauleth !
I guess I’ll keep the API reference handy as well
cheers
Rahul