Exit in Prolog

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

% Define the main predicate
main :-
    % This will be printed
    writeln('Starting the program'),
    
    % This will not be executed due to the halt/1
    setup_call_cleanup(
        writeln('Setup'),
        true,
        writeln('Cleanup')
    ),
    
    % Exit the program with status code 3
    halt(3).

% Entry point of the program
:- initialization(main).

This Prolog program demonstrates how to exit a program with a specific status code. Let’s break it down:

  1. We define a main predicate that serves as the entry point of our program.

  2. The writeln('Starting the program') line will be executed and print a message to the console.

  3. We use setup_call_cleanup/3 to demonstrate that cleanup actions won’t be performed when using halt/1. This is similar to the defer concept in the original example.

  4. The halt(3) predicate is called to immediately terminate the program with an exit status of 3. This is equivalent to os.Exit(3) in the original example.

  5. The :- initialization(main). directive ensures that the main predicate is called when the program starts.

To run this program:

  1. Save the code in a file named exit_example.pl.
  2. Use a Prolog interpreter to run the program. For example, with SWI-Prolog:
$ swipl -q -s exit_example.pl
Starting the program

The program will print “Starting the program” and then exit with status code 3.

To verify the exit status in a Unix-like shell:

$ swipl -q -s exit_example.pl
Starting the program
$ echo $?
3

Note that the “Setup” and “Cleanup” messages are never printed, as the program exits before the setup_call_cleanup/3 predicate is fully executed.

In Prolog, unlike languages like C or Go, we don’t typically use a return value from the main predicate to indicate the exit status. Instead, we use the halt/1 predicate to explicitly set the exit status when needed.

This example demonstrates how to exit a Prolog program with a specific status code, which is useful for indicating success or failure to the calling environment.