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
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With