Exit in Racket
Here’s an idiomatic Racket example that demonstrates the concept of exiting a program with a specific status code:
#lang racket
(define (main)
; This will not be executed due to early exit
(dynamic-wind
(lambda () (void))
(lambda ()
(exit 3))
(lambda ()
(displayln "This will not be printed"))))
(main)This Racket program demonstrates how to exit a program with a specific status code. Let’s break down the code and explain its components:
We define a
mainfunction that encapsulates our program’s logic.Inside
main, we usedynamic-windto set up a context with setup, body, and cleanup procedures. This is similar to thedeferconcept in some other languages.The body of
dynamic-windcontains theexitfunction call with an argument of 3. This is equivalent toos.Exit(3)in the original example.The cleanup procedure (third argument to
dynamic-wind) contains adisplaylncall that will not be executed due to the early exit.
To run this program:
- Save the code in a file named
exit-example.rkt. - Open a terminal and navigate to the directory containing the file.
- Run the program using the Racket interpreter:
$ racket exit-example.rktTo check the exit status in a Unix-like shell:
$ racket exit-example.rkt
$ echo $?
3This will display the exit status of 3, confirming that our program exited with the specified status code.
Key points to note:
- In Racket, the
exitfunction is used to terminate the program with a specific status code. - Unlike some languages, Racket doesn’t use the return value of the
mainfunction to determine the exit status. - The
dynamic-windform in this example is used to demonstrate that cleanup code (similar todeferin some languages) won’t be executed when usingexit.
This example showcases how to properly exit a Racket program with a specific status code, which can be useful for signaling success or failure to the operating system or other programs that might be calling your Racket script.