Search code examples
functional-programmingerlangtupleslist-comprehensionerl

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


Solution

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