How does one return e.g. the first element of a tuple?
I would like to take a list of 2 element tuples and return the second element of each tuple as a new list.
How does one return e.g. the first element of a tuple?
I would like to take a list of 2 element tuples and return the second element of each tuple as a new list.
1> P = {adam,24,{july,29}}.
{adam,24,{july,29}}
2> element(1,P).
adam
3> element(3,P).
{july,29}
See also: http://www.erlang.org/doc/reference_manual/data_types.html#id2259804
exactly what you've asked:
666> [element(2,X) || X <- [{1,2},{3,4}]].
[2,4]
Well, true, element/2 + comprehension will work. But the best way is to pattern match:
[ Var2 || {_Var1, Var2} <- [{1,2},{3,4}]]
Every pattern matching is superior to function call, due to code simplicity.
So, above what you have is list comprehension (double pipes inside the list). Before pipes (right hand side) there is generator, left side is a product.
General:
List = [ ReturnedValue = some_function(X) || X <- GeneratorList, X =/= Conditions ]
you could use use lists:map (not so simple like lists comprehension though):
lists:map(fun({_,X}) -> X end, [{a,b},{c,d},{e,f}]).