3

I have a list with tuples in Erlang for example:

[{1, "AAA"}, {2, "AAA"}, {3, "AAAAAAAA"}]

How can i get tuple from this list with max first element from this tuples?

Thank you.

0xAX
  • 20,957
  • 26
  • 117
  • 206

2 Answers2

5

In this case lists:max/1 will return what you want. For this to work all tuples must have the same number of elements.

Roberto Aloi
  • 30,570
  • 21
  • 75
  • 112
Arjan
  • 19,957
  • 2
  • 55
  • 48
3

Use lists:keysort/2.

1> lists:keysort(1, [{1, "AAA"}, {2, "AAA"}, {3, "AAAAAAAA"}]).

Another thread

edit: Seems I read your questions to fast. If you only want one tuple containing a maximum value and your tuples are of same size Arjan should be the accepted answer.

If you only want one term() element containing a maximum value, and if the rule with similar tuple-sizes Arjan stated doesn't apply, I would go with either a lists:foldl/3 or own recursion function.

Sorting the whole list is unnecessary unless you want the whole list sorted. My mistake.

Community
  • 1
  • 1
D.Nibon
  • 2,883
  • 1
  • 19
  • 17