I need to sort tuples according to the second element of each tuple but apparently usort/1 only works with the first element. So I have to swap the elements, usort them and swap back.Is there an easier way?Also is there a way to sort in descending order (I know sorting and reversing can be done, but just want to know).
A:
It shouldn't be too hard to write your own sort function (adapted from a common example):
qsort([]) -> [];
qsort([Pivot|Tail]) ->
{PivotFirst, PivotSecond} = Pivot,
qsort([{FirstElement, SecondElement} || {FirstElement,SecondElement} <- Tail, SecondElement < PivotSecond])
++ [Pivot] ++
qsort([{FirstElement, SecondElement} || {FirstElement,SecondElement} <- Tail, SecondElement >= PivotSecond]).
bmdhacks
2008-10-08 06:14:13
+2
A:
Actually, a better answer:
There's a second version of sort that takes a sorting function:
lists:sort(Fun, List1) -> List2
Here's an example that sorts on the second element in a tuple:
lists:sort(fun(A, B) ->
{A1, A2} = A,
{B1, B2} = B,
if
A2 > B2 ->
false;
true ->
true
end
end, YourList).
bmdhacks
2008-10-08 06:29:44
+2
A:
An improved version of bmdhacks' solution:
lists:sort(fun(A, B) ->
{_, A2} = A,
{_, B2} = B,
A2 =< B2
end, YourList).
Underscores are better then A1 and B1, because the compiler will give warnings for those.
To sort in descending order, just change <= to >=.
hcs42
2008-10-08 07:22:26
+3
A:
Have you tried keysort/2 function (or its counterpart ukeysort/2)?
> lists:reverse(lists:keysort(2, [{a,2}, {b,1}, {c, 3}])).
[{c,3},{a,2},{b,1}]
If you don't sort very big lists this is probably the most readable solution you can get.
Michał Kwiatkowski
2008-10-08 07:27:57