Exit in OCaml

Here’s an idiomatic OCaml example that demonstrates the concept of exiting a program with a specific status code:

(* Exit demonstration *)

(* Print a message before exiting *)
let print_exit_message () =
  print_endline "Exiting the program"

(* Main function *)
let main () =
  (* Register a function to be called at exit *)
  at_exit print_exit_message;
  
  (* Exit with status 3 *)
  exit 3

(* Execute the main function *)
let () = main ()

This OCaml program demonstrates how to exit a program with a specific status code. Let’s break it down:

  1. We define a function print_exit_message that prints a message. This function will be called when the program exits.

  2. The main function is where the core logic resides:

    • We use at_exit to register the print_exit_message function to be called when the program exits.
    • We call exit 3 to immediately terminate the program with an exit status of 3.
  3. The let () = main () at the bottom is the entry point of our program, which calls the main function.

To compile and run this program:

  1. Save the code in a file named exit_demo.ml.
  2. Open a terminal and navigate to the directory containing the file.
  3. Compile the code using the OCaml compiler:
$ ocamlc -o exit_demo exit_demo.ml

This will create an executable named exit_demo.

  1. Run the program:
$ ./exit_demo
Exiting the program
$ echo $?
3

You’ll notice that the “Exiting the program” message is printed, and the exit status is 3.

Key points to note:

  • Unlike some languages, OCaml doesn’t use the return value of the main function to set the exit status. Instead, we use the exit function from the standard library.
  • The at_exit function allows us to register functions that will be called when the program exits, similar to defer in some other languages.
  • OCaml doesn’t have a direct equivalent to Go’s defer, but at_exit can be used for similar purposes in some cases.

This example demonstrates how to handle program termination and exit status in OCaml, which is a common task in many programs, especially those used in shell scripts or other environments where the exit status is meaningful.