Hello World in Prolog

Published on 26 May 2024 (Updated: 19 November 2026)

Welcome to the Hello World in Prolog page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

:- initialization(main).
main():-
    write("Hello, World!\n"),
    halt.

Hello World in Prolog was written by:

This article was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

Let's walk through Hello World in Prolog, line by line.

A Prolog file is a set of facts and rules, plus directives that run while the file loads. The first line is a directive:

:- initialization(main).

It tells Prolog to call main once the whole file has been loaded. Without it, loading the file would only define main, and nothing would print until someone asked for it at the interactive prompt.

Next comes the rule that does the work. Its head is main(), and the body after :- is a list of goals separated by commas, which Prolog runs in order. The empty brackets are SWI-Prolog syntax for a term with no arguments; in a rule head, SWI-Prolog treats main() the same as plain main, so this defines main/0, the predicate the directive calls.

The first goal writes the greeting:

write("Hello, World!\n")

In SWI-Prolog, text in double quotes is a string, and write prints it as it is, with \n ending the line. That detail matters because Prolog systems disagree here: under the older convention, the same quotes make a list of character codes, and write would print a list of numbers instead of the greeting.

The last goal, halt, ends the program. Otherwise SWI-Prolog would finish loading the file and then wait at its interactive prompt.

How to Run the Solution

If we just want to see it run, we can paste the solution into an online Prolog compiler and press Run.

To run it locally, we need a Prolog system. The solution uses SWI-Prolog's string syntax, so SWI-Prolog is the one to download; it has installers for Windows and macOS, and many Linux distributions package it as swi-prolog. With swipl on our path and a copy of the solution, we can run it from the folder that holds it:

swipl hello-world.pl

SWI-Prolog loads the file, the initialization directive calls main, and Hello, World! prints to the console before halt ends the program.