1

Consider the following nested list:

[["AXY"],["ABC","XYZ"],["EFG","ACF"]]

I would like to sort the list lexicographically by the first element of each inner list. The output should be:

[["ABC","XYZ"],["AXY"],["EFG","ACF"]]

If the task have been to sort only one list, I would use one of the methods in the following thread (link). But how can I sort a nested list?

vesii
  • 2,760
  • 4
  • 25
  • 71

2 Answers2

1

Assuming you have a generic sort function taking a cmp function (like the one shown at the bottom of this answer), you just need to write one taking two string lists:

fun cmpnest ((x::xs):string list, (y::ys):string list) = if x > y then GREATER else LESS
|   cmpnest ((x::xs):string list, nil) = GREATER
|   cmpnest (nil, _) = LESS

After you have that, you can use it in your generic sort function:

- sort cmpnest [["AXY"], ["ABC", "XYZ"], ["EFG", "ACF"]];
> val it = [["ABC", "XYZ"], ["AXY"], ["EFG", "ACF"]] : string list list
L3viathan
  • 26,748
  • 2
  • 58
  • 81
1

As an addition to L3viathan's answer, you can also use String.compare:

fun cmpnest (x::_, y::_) = String.compare (x, y)
  | cmpnest (_::_, []) = GREATER
  | cmpnest ([], _) = LESS
sshine
  • 15,635
  • 1
  • 41
  • 66