Exit in Haskell
Here’s an idiomatic Haskell example that demonstrates the concept of exiting a program with a specific status code:
import System.Exit (exitWith, ExitCode(..))
import System.IO (hPutStrLn, stderr)
main :: IO ()
main = do
-- This line will be executed
putStrLn "Starting the program"
-- This line will not be executed due to exitWith
-- Haskell doesn't have a direct equivalent to Go's defer
-- but we can demonstrate a similar concept with this line
putStrLn "This line will not be printed"
-- Exit with status code 3
exitWith (ExitFailure 3)
-- This line will not be executed
putStrLn "This line will also not be printed"
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):
$ ghc Exit.hs
- Run the compiled executable:
$ ./Exit
Starting the program
- Check the exit code:
$ echo $?
3
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.