24

Given one list with one tuple:

[{4,1,144}]

How to extract the first element of the tuple inside the list:

element(1,lists:nth(1,L))

Do you have a simpler solution?

2240
  • 1,547
  • 2
  • 12
  • 30
Bertaud
  • 2,888
  • 5
  • 35
  • 48

3 Answers3

36

Try this:

1> A = [{3,1,1444}].
[{3,1,1444}]
2> [{X, _, _}] = A.
[{3,1,1444}]
3> X.
3
4> 
0xAX
  • 20,957
  • 26
  • 117
  • 206
  • 1
    I like this solution very simple ;-) – Bertaud Jan 27 '11 at 22:29
  • 4
    What if the tuple is of arbitrary length? How can I write a function to do this? – ankush981 Jul 26 '16 at 08:36
  • First of all: You should not have tuples of _arbitrary length_. In those scenarios you should use lists. But… if you insist: `AListOfTuples = generate:your_list_of_tuples(), [FirstTuple|_] = AListOfTuples, [X|_] = tuple_to_list(FirstTuple), X.` – Brujo Benavides Dec 05 '19 at 10:52
30

Given that you get exactly what you state, a list with one tuple, even easier would be (using element/2)

element(1, hd(L)).

A pattern matching variant like shk suggested is probably even nicer, depending on the context.

2240
  • 1,547
  • 2
  • 12
  • 30
E Dominique
  • 1,535
  • 13
  • 17
5

you could also consider using records syntax if you want some semantics embedded into your tuples

-record(x, {y, z}).

1> A = #x{y=b, z=c}.
2> A#x.y.
b

all records are in fact tuples and you dont have to worry about order of elements in that tuple nor about adding/removing elements.

keymone
  • 8,006
  • 1
  • 28
  • 33