lists:sort/2

Erik Stenman <>
Tue Jun 3 18:06:22 CEST 2003


I can't see that any of your functions could be right
Take the elements {1,2} and {4,1}
  {1,2} < {4,1} AND {4,1} < {1,2} !!!

You have to make a total order like:
F1 = fun ({X1,Y1},{X2,Y2}) -> if (X1 < 3) or (X2 < 3) -> X1 < X2; true -> Y1
< Y2 end end. 

Or 
 F2 = fun ({X1,Y1},{X2,Y2}) -> if (X1 < 3) and (X2 < 3) -> X1 < X2; true ->
Y1 < Y2 end end.

Depending on what you mean by "I wanted a list sorted on P for all P < 3,
and sorted on R for the remainder." (From your example I guess you want
solution 1).

6> lists:sort(F1,L).                                            
[{1,11.2000},{1,10.1000},{2,10.2000},{3,10.3000},{4,10.4000}]

> -----Original Message-----
> From:  
> [mailto:] On Behalf Of Ulf Wiger
> Sent: den 3 juni 2003 17:47
> To: 
> Subject: lists:sort/2
> 
> 
> 
> I encountered some surprising results when using
> lists:sort/2. Given a list [{P,R}], I wanted a list sorted
> on P for all P < 3, and sorted on R for the remainder.
> I tried two different funs on the same list. The second one 
> below produced the wanted result. The first one didn't. There 
> is no help from the documentation in explaining why this 
> happens, or indeed that there is a difference.
> 
> Does anyone feel acquainted enough with the sorting
> algorithm to explain the phenomenon? Am I using the function
> in a way that was never intended?
> 
> /Uffe
> 
> L = [{1, 10.1},
>      {4, 10.4},
>      {1, 11.2},
>      {3, 10.3},
>      {2, 10.2}].
>  --> [{1,10.1000},{4,10.4000},{1,11.2000},{3,10.3000},{2,10.2000}]
> 
> lists:sort(
>   fun({P1,_}, {P2,_}) when P1 < 3 ->
> 	  P1 < P2;
>      ({_,R1}, {_,R2}) ->
> 	  R1 < R2
>   end, L).
>  --> [{1,10.1000},{4,10.4000},{1,11.2000},{2,10.2000},{3,10.3000}]
> 
> lists:sort(
>   fun({P1,_}, {P2,_}) when P2 < 3 ->
> 	  P1 < P2;
>      ({_,R1}, {_,R2}) ->
> 	  R1 < R2
>   end, L).
>  --> [{1,11.2000},{1,10.1000},{2,10.2000},{3,10.3000},{4,10.4000}]
> 
> 
> /Uffe
> -- 
> Ulf Wiger, Senior Specialist,
>    / / /   Architecture & Design of Carrier-Class Software
>   / / /    Strategic Product & System Management
>  / / /     Ericsson AB, Connectivity and Control Nodes
> 
> 




More information about the erlang-questions mailing list