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

1

5

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

Cavefish answered 19/12, 2018 at 15:31 Comment(0)
C
7

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]
Cavefish answered 19/12, 2018 at 16:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.