Elixir: divide the list into odd and even elements as two elements in a tuple

I take Elixir programming calmly and do not get too stuck in breaking into two elements.

Given a list of integers, return a two-element tuple. The first element is a list of even numbers from the list. The second is a list of odd numbers.

Input : [ 1, 2, 3, 4, 5 ] Output { [ 2, 4], [ 1, 3, 5 ] } 

I have reached the definition of odd or even, but not sure how to do this.

 defmodule OddOrEven do import Integer def task(list) do Enum.reduce(list, [], fn(x, acc) -> case Integer.is_odd(x) do :true -> # how do I get this odd value listed as a tuple element :false -> # how do I get this even value listed as a tuple element end #IO.puts(x) end ) end 
+6
source share
2 answers

You can use Enum.partition/2 :

 iex(1)> require Integer iex(2)> [1, 2, 3, 4, 5] |> Enum.partition(&Integer.is_even/1) {[2, 4], [1, 3, 5]} 

If you really want to use Enum.reduce/2 , you can do this:

 iex(3)> {evens, odds} = [1, 2, 3, 4, 5] |> Enum.reduce({[], []}, fn n, {evens, odds} -> ...(3)> if Integer.is_even(n), do: {[n | evens], odds}, else: {evens, [n | odds]} ...(3)> end) {[4, 2], [5, 3, 1]} iex(4)> {Enum.reverse(evens), Enum.reverse(odds)} {[2, 4], [1, 3, 5]} 
+12
source

Or you can use the Erlang :lists module:

 iex> :lists.partition(fn (n) -> rem(n, 2) == 1 end, [1,2,3,4,5]) {[1,3,5],[2,4]} 
+2
source

All Articles