Sorting in Standard ML
(* Standard ML's List module provides sorting functionality for lists.
We'll look at sorting for built-in types first. *)
(* The `sort` function in the List module is polymorphic and works
for any type that has an ordering. *)
val strs = ["c", "a", "b"]
val sortedStrs = List.sort String.compare strs
val _ = print("Strings: " ^ String.concatWith " " sortedStrs ^ "\n")
(* An example of sorting integers *)
val ints = [7, 2, 4]
val sortedInts = List.sort Int.compare ints
val _ = print("Ints: " ^ String.concatWith " " (List.map Int.toString sortedInts) ^ "\n")
(* We can also check if a list is already in sorted order *)
fun isSorted compare [] = true
| isSorted compare [_] = true
| isSorted compare (x::y::rest) =
compare(x, y) <= EQUAL andalso isSorted compare (y::rest)
val s = isSorted Int.compare sortedInts
val _ = print("Sorted: " ^ Bool.toString s ^ "\n")This Standard ML code demonstrates sorting functionality similar to the original example. Here’s an explanation of the key points:
Standard ML uses the
Listmodule for list operations, including sorting.The
List.sortfunction is polymorphic and works with any comparable type. It takes a comparison function as its first argument.For strings, we use
String.compareas the comparison function. For integers, we useInt.compare.To print the results, we use
String.concatWithto join the list elements into a string.The
isSortedfunction is a custom implementation to check if a list is sorted. It’s defined recursively and uses the provided comparison function.Standard ML doesn’t have a built-in boolean type name, so we use
Bool.toStringto convert the boolean result to a string for printing.
To run this program, you would typically save it to a file (e.g., sorting.sml) and then use an Standard ML interpreter or compiler. For example, with the Standard ML of New Jersey (SML/NJ) system:
$ sml sorting.sml
Strings: a b c
Ints: 2 4 7
Sorted: trueThis example demonstrates how to perform sorting operations in Standard ML, showcasing its functional programming features and the use of the standard library modules.