Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the second element of a tuple in a pipeline

I want to be able to extract the Nth item of a tuple in a pipeline, without using with or otherwise breaking up the pipeline. Enum.at would work perfectly except for the fact that a tuple is not an enum.

Here's a motivating example:

colors = %{red: 1, green: 2, blue: 3}
data = [:red, :red, :blue]
data 
|> Enum.map(&Map.fetch(colors, &1))
|> Enum.unzip

This returns {[:ok, :ok, :ok], [1, 1, 3]} and let's say I just want to extract [1, 1, 3]

(For this specific case I could use fetch! but for my actual code that doesn't exist.)

I could add on

|> Tuple.to_list
|> Enum.at(1)

Is there a better way of doing this that doesn't require creating a temporary list out of each tuple?

like image 660
AnilRedshift Avatar asked May 23 '18 20:05

AnilRedshift


People also ask

How do you get the second element from a tuple?

If you need to get the second element from a list of tuples, use a list comprehension. Copied! We used a list comprehension to get a new list that contains the second element of each tuple. List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

How do you access tuple elements in Elixir?

Elixir tuples are stored contiguously in memory and are accessed by index. A tuple literal uses a pair of curly braces {} . The elem/2 function is used to access a data item in a tuple. The length of a tuple can be found with the tuple_size/1 function.

How do you take the first element of a tuple?

Use indexing to get the first element of each tuple Use a for-loop to iterate through a list of tuples. Within the for-loop, use the indexing tuple[0] to access the first element of each tuple, and append it.


2 Answers

Use Kernel.elem/2:

iex(1)> {[:ok, :ok, :ok], [1, 1, 3]} |> elem(1)
[1, 1, 3]
like image 193
Dogbert Avatar answered Oct 07 '22 11:10

Dogbert


Pattern Match can help

{ _status, required_value } = 
  data 
    |> Enum.map(&Map.fetch(colors, &1))
    |> Enum.unzip

You can ignore the _status.

like image 34
Dinesh Balasubramanian Avatar answered Oct 07 '22 12:10

Dinesh Balasubramanian