Exit in Idris
Here’s an idiomatic Idris example demonstrating the concept of exiting a program:
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:
System
for theexitWith
function andSystem.File
for theExitFailure
constructor.The
main
function 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
exitWith
function is called withExitFailure 3
as its argument. This immediately terminates the program with an exit status of 3.The last
putStrLn
statement 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:
This will create an executable named exit
.
- Run the program:
You’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.