Exit in Scheme

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

(import (scheme base)
        (scheme process-context)
        (scheme write))

;; Define a procedure that will not be called due to early exit
(define (cleanup)
  (display "Cleaning up...") (newline))

;; Main program
(define (main)
  ;; Register cleanup procedure
  (dynamic-wind
    (lambda () #f)  ; No setup needed
    (lambda ()
      ;; This message will be printed
      (display "Starting the program") (newline)
      ;; Exit with status 3
      (exit 3))
    cleanup))  ; This cleanup will not be called

;; Run the main program
(main)

This Scheme program demonstrates the concept of exiting a program with a specific status code. Let’s break it down:

  1. We import necessary modules: (scheme base) for core functionality, (scheme process-context) for the exit procedure, and (scheme write) for output procedures.

  2. We define a cleanup procedure that won’t be called due to the early exit.

  3. The main procedure is where the core logic resides:

    • We use dynamic-wind to register cleanup actions, similar to defer in some other languages.
    • We display a message indicating the program has started.
    • We call exit with status code 3, which immediately terminates the program.
  4. Finally, we call the main procedure to run our program.

To run this program:

  1. Save the code in a file, e.g., exit-example.scm.
  2. Run it using a Scheme interpreter. For example, if you’re using Chez Scheme:
$ chez --script exit-example.scm
Starting the program

To check the exit status in a shell:

$ chez --script exit-example.scm
Starting the program
$ echo $?
3

Note that the cleanup procedure is not called when using exit, similar to how defer statements are not executed in some other languages when forcefully exiting.

In Scheme, unlike languages like C, the return value of the main procedure is not used as the exit status. To exit with a non-zero status, you must explicitly use the exit procedure.

This example demonstrates how to handle program termination in Scheme, which is a fundamental concept in many programming tasks, especially when dealing with error conditions or implementing command-line tools.