Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: Get the first element of each tuple in a list

I can get the first element of every tuple if I create the list at the same time, for example

[element(2,X) || X <- [{1,2},{3,4}]].
[2,4]

This works as it should. I want to be able to create the list before I try to do anything with it

Ex: Create the list

X = [{1,2,3},{3,4,5}]. 
[{1,2,3},{3,4,5}]

Then get the first element of each tuple

element(1,X).

But I get the error

** exception error: bad argument
     in function  element/2
        called as element(1,[{1,2,3},{3,4,5}])

I want this code to give the same results that my first example gave

like image 813
Sam Avatar asked Dec 19 '18 15:12

Sam


People also ask

How do you get the first element of a tuple in a list of tuples?

We can iterate through the entire list of tuples and get first by using the index, index-0 will give the first element in each tuple in a list.

How do you get the first thing in a tuple?

To get the first element of each tuple in a list: Declare a new variable and set it to an empty list. Use a for loop to iterate over the list of tuples. On each iteration, append the first tuple element to the new list.

Is Erlang a list?

The List is a structure used to store a collection of data items. In Erlang, Lists are created by enclosing the values in square brackets.


1 Answers

Use List Comprehension with a generator(<-)

X = [{1,2,3},{3,4,5}].
[A || {A,_,_} <- X].

This is saying that we want to print element A, where A is taken from the tuple {A,_,_}(a tuple which we generate from each tuple in X). Because we are only selecting A and don't care about the second and third element, they are set equal to _.


Output

1> X = [{1,2,3},{3,4,5}].
[{1,2,3},{3,4,5}]
2> [A || {A,_,_} <- X].
[1,3]
like image 136
Sam Avatar answered Nov 15 '22 09:11

Sam