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:
We import necessary modules, including
Node.Processfor theexitfunction.The
mainfunction is defined as anEffect Unit, which is PureScript’s way of handling side effects.We use
logto print a message to the console before exiting.The
exitfunction fromNode.Processis used to immediately terminate the program with a status code of 3.Any code after the
exitcall will not be executed, similar to theos.Exitbehavior in the original example.
To run this program:
- Save the code in a file named
Main.purs. - Compile the code using the PureScript compiler:
$ spago build- Run the compiled JavaScript using Node.js:
$ node -e "require('./output/Main').main()"
Starting the programTo check the exit status:
$ echo $?
3Note 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.