DEV Community

Masaki Haga
Masaki Haga

Posted on • Updated on

How to Creat Executable Commands in Standard ML

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
Enter fullscreen mode Exit fullscreen mode

CommandLine.name () yields the command name as a string.

arguments function

- CommandLine.arguments;
val it = fn: unit -> string list
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 to EXIT_SUCCESS in C)
  • OS.Process.failure: Failure (Corresponds to EXIT_FAILURE in C)

To run a program

val arg = someFunc1
val _ = (someFunc2 arg; ...)
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode
$ mlton someCommand.sml
$ ./someCommand a b c d
Name:
./someCommand
Arguments:
1: a
2: b
3: c
4: d
Enter fullscreen mode Exit fullscreen mode

Reference

sml-family.org (Standard ML Main Site)

Top comments (0)