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:
We define a
lenCmp
function that compares strings based on their length usingString.size
.We sort the
fruits
list usingList.sort
with our customlenCmp
function.We define a
person
data type withname
andage
fields.We create a list of
people
and define anageCmp
function to compare people by age.We sort the
people
list usingList.sort
with ourageCmp
function.We define a
personToString
function to convert a person to a string for printing.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.