1

Im trying to Sort Rule-s according to Key-s (or names) but the normal Sort routine places String-s above Symbol-s. My goal is to have them Sort equally by names.

Here is the normal Sort routine. Notice that it places String names above Symbol-s.

ClearSystemCache[];
ClearAll["Global`*"];

names = {c -> 3, d -> 4, "f" -> 6, g -> 7, "a" -> 1, e -> 6, h -> 8, "b" -> 2};

Sort[names]

(* Out: {"a" -> 1, "b" -> 2, "e" -> 6, "f" -> 6, c -> 3, d -> 4, g -> 7, h -> 8} *)

Here are my two attempts at deriving a Sort function. Not good. No sorting occurs. Please help.

ClearSystemCache[];
ClearAll["Global`*"];

names = {c -> 3, d -> 4, "f" -> 6, g -> 7, "a" -> 1, "e" -> 6, h -> 8, "b" -> 2};

Sort[names, ToString[#1] < ToString[#2] &]

(* Out: {c -> 3, d -> 4, "f" -> 6, g -> 7, "a" -> 1, "e" -> 6, h -> 8, "b" -> 2} *)

p[ToString[_x], ToString[_y]] /; x > y := -1; p[ToString[_x], ToString[_y]] /; StringMatchQ[x, y] := 0; p[ToString[_x], ToString[_y]] /; x < y := 1; Sort[names, p]

(* Out: {c -> 3, d -> 4, "f" -> 6, g -> 7, "a" -> 1, "e" -> 6, h -> 8, "b" -> 2} *)

Jules Manson
  • 2,457
  • 11
  • 19

0 Answers0