Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort all levels of expression

What's a good way to Sort all levels of an expression? The following does what I want when expression has rectangular structure, but I'd like it to work for non-rectangular expressions as well

Map[Sort, {expr}, Depth[expr] - 1]

For instance, the following should print True

sorted = deepSort[{{{1, 3, 8}, {3, 7, 6}, {10, 4, 9}, {3, 8, 10, 
      6}, {8, 2, 5, 10}, {8, 5, 10, 
      9}}, {{{1, 3, 8}, {3, 8, 10, 6}}, {{3, 7, 6}, {3, 8, 10, 
       6}}, {{10, 4, 9}, {8, 5, 10, 9}}, {{3, 8, 10, 6}, {8, 2, 5, 
       10}}, {{8, 2, 5, 10}, {8, 5, 10, 9}}}}];
checkSortedLevel[k_] := Map[OrderedQ, sorted, {k}];
And @@ Flatten[checkSortedLevel /@ Range[0, 2]]
like image 339
Yaroslav Bulatov Avatar asked Feb 08 '11 22:02

Yaroslav Bulatov


2 Answers

deepSort[expr_] := Map[Sort, expr, {0, -2}]

Note that this will work even if your expr contains heads other than List.

like image 173
joebolte Avatar answered Oct 04 '22 00:10

joebolte


Should you have an expression that contains heads other than List, and you do not want to sort those, this may be useful.

expr /. List :> Composition[Sort, List]
like image 26
Mr.Wizard Avatar answered Oct 04 '22 00:10

Mr.Wizard