Exit in Standard ML
Here’s an idiomatic Standard ML example that demonstrates the concept of program exit:
This Standard ML program demonstrates how to exit a program with a specific status code. Let’s break down the code and its concepts:
We import the
OS
structure, which provides system-level operations, including process management.We define a function
printMessage
that, if called, would print a message to the console.The main program is represented by the
val _ = (...)
expression. In Standard ML, the underscore_
is used when we don’t need to bind the result to a name.We use
OS.Process.atExit printMessage
to register ourprintMessage
function to be called when the program exits normally. However, this function will not be called when we useOS.Process.exit
.Finally, we call
OS.Process.exit 3
to immediately terminate the program with an exit status of 3.
To compile and run this program:
- Save the code in a file named
Exit.sml
. - Use an Standard ML compiler like MLton to compile the program:
This will create an executable file named Exit
.
- Run the program:
You’ll notice that no output is produced, and the exit status is 3.
Important notes:
- Unlike some other languages, Standard ML doesn’t use the return value of a
main
function to determine the exit status. Instead, we explicitly callOS.Process.exit
with the desired status code. - The
atExit
function registers cleanup actions for normal program termination. However, when usingOS.Process.exit
, these cleanup actions are not performed. - Standard ML doesn’t have a direct equivalent to Go’s
defer
keyword. TheatExit
function provides similar functionality for program-wide cleanup, but it doesn’t work on a per-function basis like Go’sdefer
.
This example demonstrates how to control program exit in Standard ML, which is a crucial concept in systems programming and error handling.