tags:

views:

88

answers:

4

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.

+2  A: 
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

The MYYN
+1  A: 

exactly what you've asked:
666> [element(2,X) || X <- [{1,2},{3,4}]].
[2,4]

kr1
Thanks, but I wanted a little help understanding it, not just the code.
alJaree
alJaree, to understand you can read http://www.erlang.org/doc/programming_examples/list_comprehensions.html
taro
A: 

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 ]

About comprehension in erlang doc: http://www.erlang.org/doc/programming_examples/list_comprehensions.html
+2  A: 

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}]).

Alin
I think it's worth noting that this one probably behaves best when dealing with bad data, which can justify the slightly more complex looking syntax.
cthulahoops