Sorting By Functions in Standard ML

Our example demonstrates how to implement custom sorting in Standard ML. We’ll sort strings by their length and a custom data type by one of its fields.

(* First, we define a custom comparison function for string lengths *)
fun lenCmp (a, b) = Int.compare (String.size a, String.size b)

(* Our list of fruits to be sorted *)
val fruits = ["peach", "banana", "kiwi"]

(* We use the built-in List.sort function with our custom comparison *)
val sortedFruits = List.sort lenCmp fruits

(* Print the sorted list *)
val _ = print ("Sorted fruits: " ^ String.concatWith ", " sortedFruits ^ "\n")

(* Now let's define a custom data type *)
datatype person = Person of {name: string, age: int}

(* Our list of people *)
val people = [
    Person {name = "Jax", age = 37},
    Person {name = "TJ", age = 25},
    Person {name = "Alex", age = 72}
]

(* Custom comparison function for people, sorting by age *)
fun ageCmp (Person {age = a, ...}, Person {age = b, ...}) = Int.compare (a, b)

(* Sort the list of people *)
val sortedPeople = List.sort ageCmp people

(* Function to convert a person to a string for printing *)
fun personToString (Person {name, age}) = name ^ " (" ^ Int.toString age ^ ")"

(* Print the sorted list of people *)
val _ = print ("Sorted people: " ^ 
    String.concatWith ", " (List.map personToString sortedPeople) ^ "\n")

In this Standard ML code:

  1. We define a lenCmp function that compares strings based on their length using String.size.

  2. We sort the fruits list using List.sort with our custom lenCmp function.

  3. We define a person data type with name and age fields.

  4. We create a list of people and define an ageCmp function to compare people by age.

  5. We sort the people list using List.sort with our ageCmp function.

  6. We define a personToString function to convert a person to a string for printing.

  7. Finally, we print both sorted lists.

To run this program, save it to a file (e.g., sorting.sml) and use your Standard ML interpreter. For example, with SML/NJ:

$ sml sorting.sml
Sorted fruits: kiwi, peach, banana
Sorted people: TJ (25), Jax (37), Alex (72)

This example demonstrates how to implement custom sorting in Standard ML using the built-in List.sort function with custom comparison functions. It’s a powerful and flexible way to sort any kind of data structure in your Standard ML programs.