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:
We import the
System
namespace to useEnvironment.Exit()
andAppDomain
functionality.We define a
cleanup
function that simulates resource cleanup. This function won’t be called due to the early exit.The
main
function is marked with the[<EntryPoint>]
attribute, indicating it’s the program’s entry point.We register the
cleanup
function to run when the program exits normally usingAppDomain.CurrentDomain.ProcessExit
.We print a message to indicate that the program is about to exit.
We use
Environment.Exit(3)
to immediately terminate the program with exit code 3. This is equivalent toos.Exit(3)
in Go.The last line
0
is the default return value of themain
function, but it will never be reached due to the early exit.
To compile and run this F# program:
- Save the code in a file named
ExitExample.fs
. - Compile the program using the F# compiler:
$ fsharpc ExitExample.fs
- Run the compiled program:
$ mono ExitExample.exe
Exiting the program...
- 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()
.