Skip to main content

Hello World (first programs) · Beginner · 15 min

Hello World in Prolog with SWI-Prolog: facts, rules and queries

By Padding · Updated 18 Nov 2026
Debian 13 (swipl:11.0.0 image) · SWI-Prolog 11.0.0

You will install SWI-Prolog 11, print a greeting from the ?- prompt, run a hello.pl script, and write a small family database of facts and a rule that the engine searches for every answer.

On this page

Most languages you meet first are lists of instructions: do this, then this, then store the result here. Prolog works the other way round. You write down facts (things that are true) and rules (how new facts follow from old ones), then you ask a query. Prolog's engine searches your facts and rules for every way to make the query true and reports what it found.

There is no assignment in Prolog. A variable is not a box you put values into; it is an unknown that the engine fills in by unification, which means making two terms equal. When one path through your rules fails, the engine goes back to its last choice and tries the next option. That is called backtracking, and it is how one query can give many answers.

This tutorial uses SWI-Prolog, a widely used free Prolog system. You install SWI-Prolog 11.0.0, print a greeting at the ?- prompt, run a script, then build a small family database and ask it questions. The examples are checked on 11.0.0 and should also work on SWI-Prolog 9.2, the version Ubuntu ships.

Step 1 · Install SWI-Prolog

On Ubuntu, install from the SWI-Prolog team's own package archive (a PPA). Ubuntu 26.04's built-in package is version 9.2, which is older but should run every example in this tutorial; the PPA gives you 11.0 and keeps it updated through apt.

Bash
sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository -y ppa:swi-prolog/stable
sudo apt update
sudo apt install -y swi-prolog-nox

swi-prolog-nox is SWI-Prolog without its graphical tools, which you do not need here and which suits a server. On a desktop you can install swi-prolog instead to get the graphical debugger as well. On a prepaid data plan, the -nox package is the smaller download.

On macOS, run brew install swi-prolog, or download the macOS installer from swi-prolog.org/download/stable. On Windows, download the 64-bit installer from the same page and run it; when it asks, choose to add SWI-Prolog to the PATH for all users or the current user, so that swipl works in a terminal.

Check it worked

Bash
swipl --version

It prints something like SWI-Prolog version 11.0.0 for x86_64-linux. If you installed Ubuntu's own package, the version starts with 9.2. swipl is the name of the command on every platform.

Step 2 · Say hello at the ?- prompt

Start SWI-Prolog with no arguments:

Bash
swipl

It prints a welcome banner naming version 11.0.0, then the prompt ?-. That prompt is the top level. Everything you type there is a query: a question for Prolog to prove. Type this, including the full stop at the end, and press Enter:

Text
format("Hello, world!~n").

You see:

Text
?- format("Hello, world!~n").
Hello, world!
true.
  • format/2 (and its shorter form format/1) prints text. The /1 or /2 after a name is the number of arguments it takes; Prolog treats format/1 and format/2 as two different predicates.
  • "Hello, world!~n" is the text. Inside it, ~n means a newline. In SWI-Prolog, text in double quotes is a string. Many other Prolog systems read the same quotes as a list of character codes, so this is one of the places where SWI-Prolog differs from the ISO standard.
  • The full stop ends the query. Without it, Prolog waits for more input and shows | on the next line. Type . and press Enter.
  • true. is Prolog's answer. Printing worked, so the query was proved true.

Now give format a value to fill in:

Text
format("Hello, ~w!~n", ['Ada']).

~w writes the next item from the list in square brackets. 'Ada' in single quotes is an atom, a constant whose value is its own name. Atoms that start with a lowercase letter, such as ada, need no quotes. A word starting with a capital letter, such as Ada without quotes, would be a variable.

Check it worked

The first query prints Hello, world! and then true., and the second prints Hello, Ada! and true. Stay at the prompt for the next step.

Step 3 · See that = is not assignment

Try these queries one at a time:

Text
X = 5, Y is X + 1.
X = 5, X = 6.
X = 1 + 2.
point(A, 2) = point(1, B).

The answers look like this:

Text
?- X = 5, Y is X + 1.
X = 5,
Y = 6.

?- X = 5, X = 6.
false.

?- X = 1 + 2.
X = 1+2.

?- point(A, 2) = point(1, B).
A = 1,
B = 2.

What each one shows:

  • The comma means "and". In the first query, X = 5 unifies X with 5. is is the one operator that does arithmetic: it works out X + 1 and unifies the result with Y.
  • X = 5, X = 6 gives false. Once X is 5 within a query, it stays 5. X = 6 then asks "can 5 be made equal to 6?", the answer is no, so the whole query fails. Prolog has no statement that changes a variable's value.
  • X = 1 + 2 does not add anything. = only matches shapes, so X becomes the term 1+2. Use is when you want the number 3.
  • The last query unifies two structures. Prolog matches them part by part and fills in A from the right side and B from the left. Information flows both ways, which no assignment can do.

Type halt. and press Enter to leave the top level (or press Ctrl+D).

Check it worked

The second query prints false., and the third prints X = 1+2., not X = 3. If both match, you have seen the two rules that trip up most newcomers: variables bind once, and = matches rather than calculates.

Step 4 · Write and run hello.pl

Programs live in .pl files. Make a folder for this tutorial and write one:

Bash
mkdir -p ~/prolog-demo
cd ~/prolog-demo
cat > hello.pl <<'PL'
:- initialization(main, main).

main :-
    format("Hello, world!~n").
PL
swipl hello.pl

Line by line:

  • :- initialization(main, main). is a directive: a line starting with :- runs while the file loads. This one says "once the file is loaded, run the goal main as the program". The second main is the mode that makes SWI-Prolog halt afterwards instead of opening the ?- prompt. If the goal fails or throws an error, the program exits with a non-zero status, so scripts and shell pipelines can tell that something went wrong.
  • main :- starts a clause that defines main. Read :- as "is true if". The clause says "main is true if the format call succeeds".
  • format("Hello, world!~n"). is the body of the clause. The full stop ends the clause.

swipl hello.pl loads the file, which triggers the directive, which runs main.

Check it worked

The command prints Hello, world! and returns you to the shell, with no ?- prompt. echo $? straight afterwards prints 0.

Step 5 · Greet the name you pass on the command line

Write a second script that greets whoever you name, or the world if you name no one:

Bash
cd ~/prolog-demo
cat > greet.pl <<'PL'
:- use_module(library(main)).
:- initialization(main, main).

main([]) :-
    format("Hello, world!~n").
main([Name|_]) :-
    format("Hello, ~w!~n", [Name]).
PL
swipl greet.pl
swipl greet.pl Ada

Line by line:

  • :- use_module(library(main)). loads SWI-Prolog's main library. It provides a main that reads the words typed after the script name and calls your own main/1 with them as a list.
  • main([]) :- is the first clause of main/1. It only matches when the list is empty, which is when you typed no names.
  • main([Name|_]) :- is the second clause. [Name|_] matches a list with at least one item: the first item unifies with Name and _ stands for the rest, which you ignore.
  • Prolog tries the clauses in order and uses the first one whose head unifies with the call. Choosing between cases this way takes the place of an if statement.

The words arrive as atoms, so ~w prints them as they were typed. A name with letters outside English, such as Ọlá or Nomvula, prints correctly as long as your terminal uses UTF-8, which is the default on current Ubuntu, macOS and Windows Terminal.

Check it worked

The first run prints Hello, world! and the second prints Hello, Ada!.

Step 6 · Write facts and a rule

Now the part that makes Prolog different. Write a small family database:

Bash
cd ~/prolog-demo
cat > family.pl <<'PL'
% parent(Parent, Child): Parent is a parent of Child.
parent(amara, chidi).
parent(amara, ngozi).
parent(chidi, kofi).
parent(ngozi, zainab).
parent(ngozi, tunde).

% grandparent(G, C): G is a grandparent of C.
grandparent(G, C) :-
    parent(G, P),
    parent(P, C).
PL

What the file says:

  • % starts a comment that runs to the end of the line.
  • The five parent lines are facts: clauses with no body, true as written. amara, chidi and the other names are atoms, lowercase so they need no quotes. The order of the arguments means whatever you decide it means; the comment records the decision.
  • grandparent(G, C) :- parent(G, P), parent(P, C). is a rule. Read it as "G is a grandparent of C if G is a parent of some P, and P is a parent of C". G, C and P are variables because they start with capital letters.

There is no loop and no function body here. The file only describes relationships. How to find the answers is left to Prolog.

Check it worked

cat family.pl shows five facts and one rule, each ending in a full stop. If you load it with swipl family.pl and see no warning lines, the file is valid; type halt. to leave.

Step 7 · Ask questions and get every answer

Load the file and open the top level:

Bash
swipl family.pl

Ask who Amara's grandchildren are. After the first answer appears, press ; (semicolon) to ask for another, and keep pressing it until Prolog stops:

Text
grandparent(amara, Who).

You see something like:

Text
?- grandparent(amara, Who).
Who = kofi ;
Who = zainab ;
Who = tunde.

Here is the search behind those three answers. Prolog takes the rule and tries parent(amara, P). The first matching fact gives P = chidi, and then parent(chidi, C) gives kofi. When you press ;, Prolog backtracks: it looks for another chidi child, finds none, steps back to its earlier choice and tries the next amara fact, P = ngozi. That gives zainab, and backtracking once more gives tunde. When SWI-Prolog knows there are no more answers, it ends the last one with a full stop instead of waiting. If you press ; and nothing else is true, it prints false.

The same rule answers questions in the other direction, and you wrote no extra code for it:

Text
grandparent(G, tunde).
parent(kofi, X).

The first shows G = amara and waits; press ; and it prints false.. It waits because Prolog still has untried parent facts after the one that led to amara, so it cannot yet know amara is the only answer. The second gives false., because the database has no facts about Kofi's children. In Prolog, false means "I could not prove it from what I know", not "this is untrue in the world".

To collect every answer at once instead of pressing ;, use findall/3, then type halt.:

Text
findall(Who, grandparent(amara, Who), List).

It answers List = [kofi, zainab, tunde].

You can also run a query from the shell without opening the top level. -g gives the goal to run and -t halt stops SWI-Prolog afterwards:

Bash
cd ~/prolog-demo
swipl -g 'forall(grandparent(G, C), format("~w is a grandparent of ~w~n", [G, C]))' -t halt family.pl

forall/2 runs the first goal through every answer and the second goal once for each, so it prints a line per grandparent and grandchild pair.

Check it worked

The interactive query gives three grandchildren, kofi, zainab and tunde, in that order, and the findall query returns them as one list. The shell command prints three lines, starting with amara is a grandparent of kofi. Add a fact such as parent(kofi, efua). to the file on a new line straight after parent(ngozi, tunde)., run the shell command again, and a fourth line appears, chidi is a grandparent of efua, without any change to the rule.

Step 8 · Learn the common mistakes and clean up

These are the errors most people meet in their first week of Prolog:

  • A missing full stop. At the prompt, Prolog shows | and waits. In a file, you get a Syntax error with a line number; check the end of the clause before it.
  • A name written with a capital letter. parent(Amara, chidi). makes Amara a variable, so the fact means "everyone is a parent of chidi". SWI-Prolog warns Singleton variables: [Amara] when it loads the file. Keep atoms lowercase, or quote them: 'Amara'.
  • Expecting = to calculate. X = 2 * 3 gives the term 2*3. Use X is 2 * 3.
  • Trying to change a variable. X = X + 1 can never be true. Use a new variable: X1 is X + 1.
  • Clauses of one predicate spread around the file. SWI-Prolog warns Clauses of parent/2 are not together in the source-file. Keep all clauses with the same name and arity next to each other.
  • A query that seems to hang. If one answer is shown and the cursor waits, Prolog is asking whether you want more. Press ; for the next answer or Enter to stop.

See the singleton warning for yourself:

Bash
cd ~/prolog-demo
cat > typo.pl <<'PL'
parent(Amara, chidi).
PL
swipl -g halt typo.pl

Where Prolog is used

Prolog came out of research on natural language by Alain Colmerauer's group in Marseille in the early 1970s, and language processing is still one of its strengths: its grammar rules (DCGs) parse text directly. It is used for rules engines that check eligibility, configuration and compliance, where the rules change more often than the code should; for scheduling and timetabling with constraint libraries; and for teaching symbolic AI, the logic-based branch of AI that came before machine learning. SWI-Prolog also runs web services and research tools; its own website is served by SWI-Prolog.

When you are done, remove the tutorial folder:

Bash
cd ~
rm -rf ~/prolog-demo

Check it worked

Loading typo.pl prints a warning that names Singleton variables: [Amara]. After the cleanup, ls ~/prolog-demo reports No such file or directory, and swipl --version still prints your version, because deleting the folder does not touch SWI-Prolog.

Next steps

  • See a language whose syntax borrowed from Prolog: Hello World in Erlang.
  • Try another language from early AI research: Hello World in Common Lisp.
  • Compare pattern matching in a typed functional language: Hello World in Haskell.
  • The SWI-Prolog manual at swi-prolog.org covers lists, recursion and DCG grammars, the natural next topics after this one.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.