Standard ML programs are often used in interactive shells(?) However, we can not only use it in an interactive shell, but also compile it to create executable commands.
To get a command name and arguments
In Standard ML, CommandLine structure provides name function and arguments. Command names and command line arguments will be obtained by them.
name function
— CommandLine.name;
val it = fn: unit -> string
CommandLine.name () yields the command name as a string.
arguments function
- CommandLine.arguments;
val it = fn: unit -> string list
CommandLine.arguments () gives command line arguments as a list of string types.
Termination process
To close the program and return to the shell, use the Process.exit function of OS structure.
- OS.Process.exit
val it = OS.Process.status -> 'a
The argument OS.Process.status is an exit status data type to pass to the shell. There are two types:
-
OS.Process.success: Success (Corresponds toEXIT_SUCCESSin C) -
OS.Process.failure: Failure (Corresponds toEXIT_FAILUREin C)
To run a program
val arg = someFunc1
val _ = (someFunc2 arg; ...)
You can execute defined functions by evaluating them at the top level. The return value of functions should be discarded using an underscore or serial execution if they only use side effects.
Example
If you compile it with mlton, it becomes an executable.
(* someCommand.sml *)
val n = ref 0
fun prName () = print ("Name: \n" ^ CommandLine.name () ^ " \n")
fun prArg () = foldl (fn (z, unt) => print ((n := !n + 1; Int.toString (!n)) ^ ":" ^ z ^ " \n")) (print "Arguments: \n") (CommandLine.arguments ())
val _ = (prName (); prArg (); OS.Process.exit (OS.Process.success))
$ mlton someCommand.sml
$ ./someCommand a b c d
Name:
./someCommand
Arguments:
1: a
2: b
3: c
4: d
Top comments (0)