Exit in Idris
Here’s an idiomatic Idris example demonstrating the concept of exiting a program:
module Main
import System
import System.File
main : IO ()
main = do
-- This will not be executed due to the early exit
let _ = putStrLn "This won't be printed!"
-- Exit the program with status code 3
exitWith (ExitFailure 3)
-- This line will never be reached
putStrLn "This also won't be printed!"This Idris program demonstrates how to exit a program immediately with a specific status code. Let’s break down the code and explain its components:
We import the necessary modules:
Systemfor theexitWithfunction andSystem.Filefor theExitFailureconstructor.The
mainfunction is defined as anIO ()action, which is the entry point of our Idris program.We use
let _ = putStrLn "This won't be printed!"to demonstrate that this line will not be executed due to the early exit. The_is used to ignore the result ofputStrLn.The
exitWithfunction is called withExitFailure 3as its argument. This immediately terminates the program with an exit status of 3.The last
putStrLnstatement will never be reached due to the early exit.
To compile and run this Idris program:
- Save the code in a file named
Exit.idr. - Compile the program using the Idris compiler:
$ idris -o exit Exit.idrThis will create an executable named exit.
- Run the program:
$ ./exit
$ echo $?
3You’ll notice that nothing is printed to the console, and the exit status is 3.
In Idris, unlike some other languages, we don’t return an integer from the main function to indicate the exit status. Instead, we use the exitWith function to explicitly set the exit status.
The ExitFailure constructor is used to represent non-zero exit codes, while ExitSuccess represents a zero exit code. This approach provides type safety and clarity when working with exit codes.
This example demonstrates how Idris handles program termination and exit codes, which is particularly useful for command-line applications or scripts where the exit status is important for error handling and process control.