Exit in PureScript

Here’s an idiomatic PureScript example demonstrating the concept of exiting a program:

module Main where

import Prelude
import Effect (Effect)
import Effect.Console (log)
import Node.Process (exit)

main :: Effect Unit
main = do
  -- This will be executed
  log "Starting the program"

  -- Exit with status code 3
  exit 3

  -- This will not be executed
  log "This message will never be printed"

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

  1. We import necessary modules, including Node.Process for the exit function.

  2. The main function is defined as an Effect Unit, which is PureScript’s way of handling side effects.

  3. We use log to print a message to the console before exiting.

  4. The exit function from Node.Process is used to immediately terminate the program with a status code of 3.

  5. Any code after the exit call will not be executed, similar to the os.Exit behavior in the original example.

To run this program:

  1. Save the code in a file named Main.purs.
  2. Compile the code using the PureScript compiler:
$ spago build
  1. Run the compiled JavaScript using Node.js:
$ node -e "require('./output/Main').main()"
Starting the program

To check the exit status:

$ echo $?
3

Note that the second log message is never printed, as the program exits before reaching that line.

In PureScript, unlike some other languages, the main function doesn’t return an exit code. Instead, you need to explicitly call exit to terminate the program with a non-zero status code.

This example showcases how PureScript, a purely functional language, handles program termination and side effects in a type-safe manner while still providing low-level control over process exit status.