Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 40 ยท Getting Started

Your First Prolog Program: Hello World, write and format

Write and run a first Prolog program: hello world, write/1, nl/0, format/2 directives, the main predicate, initialization and a loop over all answers with forall/2.

You now know what Prolog terms look like and how to start a system. Time to write a complete program that prints something. Along the way you will meet the output predicates you will use in every program, and one important idea: a Prolog "program" is a set of predicates that the toplevel or a main predicate calls.

The prolog blocks in this lesson are read-only: run them in SWI-Prolog on your computer. The Python stand-ins let you reproduce what they do.

Hello, world

Create hello.pl:

PROLOG
hello :-
    write('Hello, world!'),
    nl.

Load it (swipl hello.pl) and ask the query hello. at the prompt:

TEXT
?- hello.
Hello, world!
true.

write/1 prints a term. nl/0 prints a newline. The final true. is the toplevel telling you that the query succeeded; it is not part of the output. The body write(...), nl is a conjunction: first print, then print a newline. Because Prolog tries the goals left to right, the order is the order of printing.

To run the program without typing at the prompt, add a directive:

PROLOG
:- initialization(main).

main :-
    write('Hello, world!'), nl.

and start swipl -q hello.pl (the -q hides the banner). The greeting is printed once the file is loaded, then the toplevel appears. Use swipl -g main -t halt hello.pl to run and exit.

write, print, writeq and write_canonical

These predicates differ in how they show terms:

PROLOG
?- write('Hello World'), nl.
Hello World

?- writeq('Hello World'), nl.
'Hello World'

?- write_canonical([1, 2, 3]), nl.
[1,2,3]

?- print(point(1, 2)), nl.
point(1,2)

write shows text as is. writeq adds quotes where needed so the output could be read back as the same term. write_canonical ignores operators and shows the plain structure. print uses portray_clause-like settings and is handy for debugging. Variables print as _G123-style names (for example _12345) because they have no name at run time.

format/2: the printing workhorse

format(Template, Arguments) fills directives in the template from a list of arguments. It is the Prolog equivalent of printf.

Directive Meaning
~w write the next argument
~q writeq the next argument
~a write an atom
~d write an integer (error if it is not one)
~2f float with 2 decimals
~s write a string given as a code list
~n newline
~t and `~N `
~~ a literal tilde
PROLOG
?- format("~w is ~d years old~n", [tom, 30]).
tom is 30 years old
true.

?- format("Pi is about ~2f~n", [3.14159]).
Pi is about 3.14
true.

?- format("~a~t~10|~a~n", [name, value]).
name      value
true.

If you have a single argument that is not a list, you can leave out the brackets: format("Hello ~w~n", world). A wrong number of arguments raises an error, so count your directives.

A program that uses facts

Programs usually combine a database with printing. Here is a small one:

PROLOG
city(oslo, norway).
city(lima, peru).
city(kyoto, japan).

show_city(City) :-
    city(City, Country),
    format("~w is in ~w~n", [City, Country]).

?- show_city(lima). prints lima is in peru. If the query is ?- show_city(C)., Prolog prints the text for oslo, then answers C = oslo and waits. It prints only one city so far; the next section fixes that.

Printing every answer: forall and fail-driven loops

To print for all cities, use forall(Condition, Action): it checks that the action succeeds for every solution of the condition.

PROLOG
list_cities :-
    forall(city(City, Country),
           format("~w is in ~w~n", [City, Country])).
TEXT
?- list_cities.
oslo is in norway
lima is in peru
kyoto is in japan
true.

Older code does the same with a failure-driven loop. fail always fails, which makes Prolog backtrack into city/2 for the next solution; when no solutions remain, a second clause makes the whole predicate succeed:

PROLOG
list_cities2 :-
    city(City, Country),
    format("~w is in ~w~n", [City, Country]),
    fail.
list_cities2.

Both versions rely on backtracking, which you will study soon. For counting from one to five use between/3:

PROLOG
?- forall(between(1, 5, N), (write(N), write(' '))), nl.
1 2 3 4 5 
true.

Reading input

read/1 reads a Prolog term typed by the user, ended with a full stop:

PROLOG
ask_name :-
    write('Your name? '),
    read(Name),
    format("Hello, ~w!~n", [Name]).

At the prompt type ann. (with the dot) and the program replies Hello, ann!. For free text use read_term(user_input, X, []) or read_line_to_string(user_input, Line).

Mimicking format in the stand-in

Python has no ~w, but we can write a tiny version to see how a template is filled. The function below understands ~w, ~a, ~d and ~n.

Python A tiny format/2 (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A fail-driven loop, step by step

The second stand-in does what list_cities does: it asks the engine for every solution of city(City, Country) and prints one line per solution. Behind the scenes solve is a generator, and asking it for the next value is exactly what Prolog's backtracking does.

Python forall over all solutions (mini-Prolog stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Missing full stop at the end of a clause, which makes the next line part of it.
  • Using write for formatted output with many pieces; prefer format.
  • Expecting write(X) to print a number from X = 3 + 4 as 7; it prints 3+4.
  • Forgetting that a directive such as :- initialization(main). runs after loading the file.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which predicate prints a newline?

    nl/0 outputs a newline. format directive ~n does the same inside a template.
  2. 2. What does format("~w-wn", [a, b]) print?

    Each ~w consumes the next argument and ~n prints a newline.
  3. 3. What is the difference between write and writeq?

    writeq('Hello World') prints 'Hello World' with quotes; write prints Hello World.
  4. 4. What does forall(Cond, Action) check?

    forall is a universal check and also a convenient way to loop for side effects like printing.

Summary

  • A program is a set of clauses; run it by querying a predicate or with initialization(main).
  • write/1, writeq/1, print/1 and nl/0 print terms; format/2 fills ~w, ~d, ~a, ~n templates.
  • forall/2 or a fail-driven loop prints every solution.
  • read/1 reads a term typed with a final full stop.

Next: Facts and Queries