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:

  1. We import exitWith and ExitCode from System.Exit to handle program termination.

  2. The main function is the entry point of our Haskell program.

  3. We use putStrLn to print messages to the console.

  4. exitWith (ExitFailure 3) is used to immediately terminate the program with an exit code of 3. This is equivalent to os.Exit(3) in Go.

  5. Any code after exitWith will not be executed, similar to how defered functions in Go are not called when using os.Exit.

To run this program:

  1. Save the code in a file named Exit.hs.
  2. Compile the program using GHC (Glasgow Haskell Compiler):
$ ghc Exit.hs
  1. Run the compiled executable:
$ ./Exit
Starting the program
  1. 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.