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.
In this Standard ML code:
We define a lenCmp function that compares strings based on their length using String.size.
We sort the fruits list using List.sort with our custom lenCmp function.
We define a person data type with name and age fields.
We create a list of people and define an ageCmp function to compare people by age.
We sort the people list using List.sort with our ageCmp 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:
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.