Command Line Arguments in Standard ML

Command-line arguments are a common way to parameterize execution of programs. For example, sml program.sml uses program.sml as an argument to the sml interpreter.

(* Command-Line Arguments *)

(* The CommandLine structure provides access to command-line arguments *)
let
    (* CommandLine.name() returns the name of the program *)
    val argsWithProg = CommandLine.name() :: CommandLine.arguments()
    
    (* CommandLine.arguments() returns a list of command-line arguments *)
    val argsWithoutProg = CommandLine.arguments()

    (* You can get individual args with normal list operations *)
    val arg = List.nth(CommandLine.arguments(), 2)
in
    (* Print the arguments *)
    print(String.concatWith " " argsWithProg ^ "\n");
    print(String.concatWith " " argsWithoutProg ^ "\n");
    print(arg ^ "\n")
end;

To experiment with command-line arguments, it’s best to save this code in a file (e.g., command_line_arguments.sml) and run it with the SML interpreter.

$ sml command_line_arguments.sml a b c d
command_line_arguments.sml a b c d
a b c d
c

In Standard ML, we use the CommandLine structure to access command-line arguments. CommandLine.name() gives us the program name, and CommandLine.arguments() provides a list of the arguments.

Unlike in some other languages, Standard ML doesn’t have a direct equivalent to slicing a list from the second element onwards. Instead, we separate the program name and arguments into two different values.

To access a specific argument, we use List.nth(), which is zero-indexed. Be careful when using this, as it will raise an exception if the index is out of bounds.

Next, we’ll look at more advanced command-line processing techniques in Standard ML.