To print "Hello, World!" in the Prolog interpreter (here we are using swipl
, the shell for SWI Prolog):
$ swipl
<...banner...>
?- write('Hello, World!'), nl.
?-
is the system prompt: it indicates that the system is ready for the user to enter a sequence of goals (i.e. a query) that must be terminated with a .
(full stop).
Here the query write('Hello World!'), nl
has two goals:
write('Hello World!')
: 'Hello World!'
has to be displayed and (,
)nl
) must follow.write/1
(the /1
is used to indicate that the predicate takes one argument) and nl/0
are built-in predicates (the definition is provided in advance by the Prolog system). Built-in predicates provide facilities that cannot be obtained by pure Prolog definition or to save the programmer from having to define them.
The output:
Hello, World!
yes
ends with yes
meaning that the query has succeeded. In some systems true
is printed instead of yes
.
Open a new file called hello_world.pl
and insert the following text:
:- initialization hello_world, halt.
hello_world :-
write('Hello, World!'), nl.
The initialization
directive specifies that the goal hello_world, halt
should be called when the file is loaded. halt
exits the program.
This file can then be executed by your Prolog executable. The exact flags depend on the Prolog system. If you are using SWI Prolog:
$ swipl -q -l hello_world.pl
This will produce output Hello, World!
. The -q
flag suppresses the banner that usually displays when you call run swipl
. The -l
specifies a file to load.