Exit in F#

Here’s an idiomatic F# example that demonstrates the concept of program exit:

open System

// This function will not be executed due to early exit
let cleanup() =
    printfn "Cleaning up resources..."

[<EntryPoint>]
let main argv =
    // Register the cleanup function to run when the program exits normally
    AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> cleanup())

    // Print a message
    printfn "Exiting the program..."

    // Exit the program with status code 3
    Environment.Exit(3)

    // This line will never be reached
    0

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

  1. We import the System namespace to use Environment.Exit() and AppDomain functionality.

  2. We define a cleanup function that simulates resource cleanup. This function won’t be called due to the early exit.

  3. The main function is marked with the [<EntryPoint>] attribute, indicating it’s the program’s entry point.

  4. We register the cleanup function to run when the program exits normally using AppDomain.CurrentDomain.ProcessExit.

  5. We print a message to indicate that the program is about to exit.

  6. We use Environment.Exit(3) to immediately terminate the program with exit code 3. This is equivalent to os.Exit(3) in Go.

  7. The last line 0 is the default return value of the main function, but it will never be reached due to the early exit.

To compile and run this F# program:

  1. Save the code in a file named ExitExample.fs.
  2. Compile the program using the F# compiler:
$ fsharpc ExitExample.fs
  1. Run the compiled program:
$ mono ExitExample.exe
Exiting the program...
  1. Check the exit code:
$ echo $?
3

Note that the cleanup function is not called when using Environment.Exit(), similar to how defer statements are not executed when using os.Exit() in Go.

In F#, like in many other .NET languages, you typically return an integer from the main function to indicate the exit status. However, using Environment.Exit() allows you to exit the program immediately from any point in your code, which can be useful in certain scenarios.

This example demonstrates how to handle program exit in F#, showing both the typical approach of returning from main and the immediate exit using Environment.Exit().