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:
We define a
mainpredicate that serves as the entry point of our program.The
writeln('Starting the program')line will be executed and print a message to the console.We use
setup_call_cleanup/3to demonstrate that cleanup actions won’t be performed when usinghalt/1. This is similar to thedeferconcept in the original example.The
halt(3)predicate is called to immediately terminate the program with an exit status of 3. This is equivalent toos.Exit(3)in the original example.The
:- initialization(main).directive ensures that themainpredicate is called when the program starts.
To run this program:
- Save the code in a file named
exit_example.pl. - Use a Prolog interpreter to run the program. For example, with SWI-Prolog:
$ swipl -q -s exit_example.pl
Starting the programThe 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 $?
3Note 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.