Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
883 views
in Technique[技术] by (71.8m points)

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

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 a list of the even numbers from the list. The second is a list of the odd numbers.

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

I have reached to identify the odd or even but not sure how do I proceed.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...