Exit in Haskell
Here’s an idiomatic Haskell example that demonstrates the concept of exiting a program with a specific status code:
This Haskell program demonstrates how to exit a program with a specific status code. Let’s break down the key points:
We import
exitWith
andExitCode
fromSystem.Exit
to handle program termination.The
main
function is the entry point of our Haskell program.We use
putStrLn
to print messages to the console.exitWith (ExitFailure 3)
is used to immediately terminate the program with an exit code of 3. This is equivalent toos.Exit(3)
in Go.Any code after
exitWith
will not be executed, similar to howdefer
ed functions in Go are not called when usingos.Exit
.
To run this program:
- Save the code in a file named
Exit.hs
. - Compile the program using GHC (Glasgow Haskell Compiler):
- Run the compiled executable:
- Check the exit code:
Note that the lines after exitWith
are not executed, and the program exits with status code 3.
In Haskell, unlike Go, we don’t use defer
for cleanup actions. Instead, we typically use bracket patterns or the bracket
function from Control.Exception
for resource management. However, these won’t be executed if we use exitWith
, just like defer
in Go.
Also, Haskell’s main
function doesn’t return an exit code directly. To exit with a non-zero status, we must use exitWith
or related functions from System.Exit
.
This example demonstrates how to handle program termination with specific exit codes in Haskell, which is a common requirement in system programming and script writing.