Elixir: Split list into odd and even elements as two items in tuple

后端 未结 2 1608
没有蜡笔的小新
没有蜡笔的小新 2020-12-19 03:46

I am quiet new to Elixir programming and stuck badly at splitting into two elements tuple.

Given a list of integers, return a two element tuple. The first element is

相关标签:
2条回答
  • 2020-12-19 04:30

    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]}
    
    0 讨论(0)
  • 2020-12-19 04:34

    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]}
    
    0 讨论(0)
提交回复
热议问题