Skip to content
Image with logo, providing a link to the home page
  • United Stated of America flag, representing the option for the English language.
  • Bandeira do Brasil, simbolizando a opção pelo idioma Português do Brasil.

Development Environments: Prolog Programming Setup

In the left, SWI Prolog's graphical environment with a REPL session and the PceEmacs editor. In the right, an example of the built-in Prolog documentation for the keyword `format`, in a `Konsole` terminal session on Linux.

Image credits: Image created by the author using the program Spectacle.

Requirements

The requirements to start programming activities with Prolog are similar to those described for JavaScript, Python, and Lua: a text editor and an interpreter, or an Integrated Development Environment (IDE).

To avoid repeating the discussions from JavaScript and Python:

  1. If you already have a text editor, you can install a Prolog interpreter to start programming using the language;
  2. If you would rather use an IDE, the simplest option is choosing SWI-Prolog and install SWI-Prolog-Editor;
  3. If you do now know how to install program, what is PATH or how to configure it, you can refer the topic regarding how to install programs.

Part of the contents of this page will be identical to the Python's page. Therefore, if certain paragraphs seem familiar, it will not an impression, but déjà vu. As a matter of fact, this will also occur in new entries about development environments for other programming languages. After all, the setup procedures are similar.

Prolog as the First Programming Language

Python and Lua lead my list of recommended programming languages for beginners, as previously commented in introduction about development environments; the third option is JavaScript, due to the Internet.

Like LISP, Prolog as a first language may be an option for some people. In particular, people who like logic and are interested in Artificial Intelligence (AI) may enjoy the language.

There are also academic research using Prolog to teach programming and AI to children.

Nevertheless, a possible obstacle for choosing Prolog as a first programming language it not exactly the language, but rather the number of people how know the language. Except via Internet, it may be hard to ask for help. It is more likely knowing someone who program in languages such as JavaScript, Python, Lua, Java or C# than Prolog. Thus, people who do not describe themselves as self-learners may have more difficulties to start learning programming using Prolog.

About Prolog

Programming in Logic or simply Prolog is a programming language that adopts the logical paradigm. The language is a good option for AI, natural language processing, export systems, and automated planning algorithms.

Like LISP, to program in Prolog, one must think differently than in other languages. Prolog is a different language because, often, you will not model solutions, but the problem using data and rules.

The programmer describes and model data and rules, ask the Prolog interpreter, and the inference engine tries to find an answer based on the model. In other words, the approach is the contrary of virtually every other programming paradigm, in which the machine is instructed how to solve a problem.

The logic paradigm allows obtaining solutions or approximations to some classes of problems that may be more complex in other paradigms. For instance, problems regarding set theory, constraint satisfaction problems (constraint solvers), and boolean satisfiability problems. However, this does not mean that the language can solve them efficiently, though this is a problem to every programming language (refer to NP-complete). Likewise, other languages can achieve the same results for the problems, though this might require more efforts.

For Prolog documentation, one can refer to:

  • The documentation provided the function help(). For instance, help(format). (the dot is part of the command);
  • SWI-Prolog documentation. If you another distribution, consult the specific documentation. Though consult the SWI Prolog can be interesting for other distributions as well.
  • GNU Prolog, as an example of documentation for another distribution.

Versions and Implementations

There are multiple Prolog implementations to choose. For instance:

There are also implementations to be embedded in other programming languages, such as Tau Prolog for JavaScript, or even libraries to use SWI-Prolog in C++.

Additional Remarks

The remainder of this text assumes the use of SWI-Prolog. Furthermore, to allow comparisons with other program languages, the examples provided in this page will be sufficiently good to highlight the qualities of Prolog.

Interpreter and Text Editor

You should use root or administrator accounts only to install the interpreter. After the installation, use a regular user account, with lower privileges, to run the interpreter and program using it.

Linux

Linux's distributions may offer different Common Lisp implementations (such as SWI-Prolog or GNU Prolog). The following examples assume the installation of SWI-Prolog.

  1. Arch Linux:
    pacman -S swi-prolog
  2. Debian, Ubuntu or distributions based on the former ones:
    apt-get install swi-prolog
  3. Fedora:
    dnf install pl
  4. Gentoo:
    emerge --ask dev-lang/swi-prolog

macOS

On macOS environments, you can use brew to install SWI-Prolog.

Windows

To install SWI Prolog on Windows, you should get the installer from the project's downloads page. In most cases, you should choose the 64-bit version (SWI-Prolog 8.4.0-1 for Microsoft Windows (64 bit)). If you have a very old computer, you might have to pick the 32-bit version (SWI-Prolog 8.4.0-1 for Microsoft Windows (32 bit)) instead.

During the set-up, it is convenient to automatically add the interpreter to the PATH (you can either choose to add it to all users or just to the current one). It may also be convenient to create a shortcut to the program in the desktop.

Enabling the options to add SWI Prolog to the `PATH` and a desktop shortcut.

When the installer asks which resources it should install, you can keep all options enabled. Although some features are not necessary for beginners, the total installation size is relatively small (around 42.1 MB for the 64-bit 8.4.0-1 version).

After the installation finishes, you can use SWI Prolog in the cmd terminal via swipl (if it was added to the PATH). Otherwise, you can use the desktop shortcut (if it was created) or search the program in the Start menu (search for swi-prolog).

Should you wish to manually add the interpreter to the PATH, refer to how to install programs.

Alternatives to install the interpreter on Windows include:

Environment Test

You can start to program in Prolog after installing the interpreter. To start the interpreter, with use the downloaded executable or type swipl followed by enter in a command line interpreter (this requires PATH configuration for files manually downloaded).

swiplWelcome to SWI-Prolog (threaded, 64 bits, version 8.4.0)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit https://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

?-

This section presents the same examples used in JavaScript and Python for purposes of testing and comparing the languages.

As in Python, you will type your code after the question mark and the dash (?-).

For instance, you can write on the console with writeln() (documentation). To write a message, type something like writeln("Hello! My name is Franco."). after the question mark and the dash, and press enter. The interpreter will write Hello! My name is Franco. and will wait your next command. The dot after the command is required.

swiplWelcome to SWI-Prolog (threaded, 64 bits, version 8.4.0)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit https://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

?- writeln("Hello! My name is Franco.").Hello! My name is Franco.
true.

?-

The text in the images are from the Portuguese version of this page.

An example of starting and using a Prolog interpreter in the command line. Use `swipl` to start the interpreter; inside it, you can write code. The image presents examples of running code presented on this section.

From now on, you should follow the previous steps whenever you read a Prolog source code block in this page and wish to manually run in the interpreter.

To exit the interpreter, type halt. followed by enter or press Ctrl d. On Windows, the shortcut can be Ctrl z followed by enter (or it may work not, requiring the use of halt.).

Like Python, Prolog can be used in a Read, Eval, Print, Loop (REPL) mode. For instance, X is 1 + 1 performs a sum.

X is 1 + 1.

On the other hand, it is not possible to write a string directly.

"Hello! My name is Franco." % Errror.

However, you should note that, as in Python, those direct uses are only possible for interactive use, that is, in REPL style. They are convenient ways to inspect values and variables, though they are not permitted in programs. If you wish to perform the same operations in a source code file (a script), you should use writeln() to write the results.

X is 1 + 1, writeln(X).
writeln("Hello! My name is Franco.").

Thus, it can be convenient to create the habit of using princ() when you want to write in the console. For instance, create a file called script.pl (you can choose any name that you want) with the following contents:

main :-
    writeln("My First Prolog Script"),
    writeln("Hello! My name is Franco."),
    writeln("The interpreter can do Math."),
    write("Check it out: "), X is 1 + 1, writeln(X),
    writeln("Bye!").

The script introduces a new function called write() (documentation), that is like writeln(), though it does not a line break after the text.

To run the script, open a command line interpreter (shell) in the directory that you have created the file and type swipl -q -f script.pl -t main . The Prolog interpreter will run the file provided as a parameter (the value script.pl after swipl -q -f) and will show results from writeln() calls.

swipl -q -f script.pl -t mainMy First Prolog Script
Hello! My name is Franco.
The interpreter can do Math.
Check it out: 2
Bye!

If the current directory of command line interpreter (shell) is not the directory of the file, you can change directory to the file's folder, or you can write the absolute path of the file. Examples for absolute file paths can include C:\Users\Franco\Desktop\script.pl on Windows for a file in the desktop of a user account named Franco or ~/Desktop/script.pl for a file in the desktop of a Linux machine.

Example of running the `script.pl` in the command line. The image shows the performed command (`swipl -q -f script.pl -t main`) and the results its execution.

If you do not want to use write() and writeln() to write results, you can use format() (documentation) instead.

main :-
    writeln("My First Prolog Script"),
    writeln("Hello! My name is Franco."),
    writeln("The interpreter can do Math."),
    X is 1 + 1, format("Check it out: ~d\n", X),
    writeln("Bye!").

In this case, ~\n inserts a line break, while ~d allows writing an integer number calculated as the result of an expression.

Finally, it is useful to know it is possible to refer to a function's documentation using the REPL. To do that, you can use the function describe().

help(format).4.32 Formatted Write

The current version of SWI-Prolog provides two formatted write predicates. The'writef'  family (
writef/1, writef/2, swritef/3), is compatible with Edinburgh C-Prolog  and should  be considered
deprecated. The'format' family (format/1, format/2, format/3), was defined by Quintus Prolog and
currently available in many Prolog systems, although the details vary.
      (...)

help(format/2).format(+Format, :Arguments)
    Format is an  atom, list  of character  codes, or  a Prolog  string. Arguments  provides the
    arguments required by the format specification. If only  one argument  is required  and this
    single  argument is  not a  list, the  argument need  not be  put in  a list.  Otherwise the
    arguments are put in a list.
      (...)

To quit the help, press q.

It is enough to know how to use the REPL and run a Prolog source code file for learning activities. In general, these two operations are also enough for most daily or professional uses of the programming language.

IDEs

The same considerations about the use of IDEs in Python apply to Prolog. The convenience, especially for beginners, continues to be a benefit from using IDEs.

The option to run code with a single click also applies to Prolog. In particular, search for the option to run a project with a single click (normally on a triangle icon (🢒) commonly used to play content eletroelectronics) or with a key press (usually F5). Furthermore, remember shortcuts for text editors, such as Ctrl n (or File / New) to create new files and Ctrl o (or File / Open) to open existing files.

Swi Prolog

The default SWI Prolog set-up includes some editors and IDE features.

Interpreter in Graphical Environment

The first option is using the interpreter in a graphical environment, accessed using swip-win. The program provides some conveniences to load files from a menu, and it can be easier use than a command line interpreter.

A practical feature is the option to consult files, available in File, then Consult.... The option allows loading data and programs to use in the REPL. For instance, to load a Prolog script such as the one defined in script.pl, you can consult the previous file. Next, you type the name of created predicate followed by a dot (main.) to evaluate the code defined in the script.

In the image, the script is called hello.pl, though it has the same contents.

Example of consulting a script using the SWI Prolog graphical environment.

The graphical environment provides two additional resources: PceEmacs and Prolog Navigator.

PceEmacs

To use PceEmacs, you should type emacs. and press enter on the graphical environment (swipl-win). PceEmacs is an alternative implementation of the Emacs editor written in Prolog. Similarly to Emacs supporting customization with Emacs Lisp, PceEmacs can be customized using Prolog.

Example of using PceEmacs with the code from `script.pl` loaded into a file called `hello.pl`.

For instruction on how to use it, you can check the documentação.

Prolog Navigator

The second feature is a menu to list files called Prolog Navigator. To enabled it, you can click on File, then on Navigator....

Example of accessing the documentation with Prolog Navigator.

Besides listing directories and files, the navigator can quickly open the documentation for predicates used in a Prolog program. To do this, you can double-click on the predicate name, or right-click once, then choosing Manual in the context menu.

SWISH Notebooks

Similarly to Jupyter for Python, SWI Prolog provides SWISH Notebooks. It can be a good option for people who like to write notes while they are studying.

SWISH Notebooks can also be used online. This can be useful, for instance, to try the language before installing it.

SWI-Prolog-Editor

An option resembling a traditional IDE is SWI-Prolog-Editor. The program includes some translations (such as European Portuguese).

Exemplo de uso de SWI-Prolog-Editor com o código de `script.pl` carregado em um arquivo chamado `hello.pl`.

To use the IDE, you should install SWI Prolog first. Then, to configure it, you click on Window then in Configuration. In Programs, you should set the Prolog directory. The default SWI Prolog's install directory on Windows is C:\Program Files\swipl (for the 64-bit version).

Other Options

Other examples for IDEs can include:

For other IDE options, there are programs supporting extensions.

First Steps to Begin Programming in Prolog

The following source code snippets illustrate some resources of the Prolog programming language. At this time, it is not necessary to fully understand them; the purpose is showing resources and the syntax of the language.

There are three ways of using the code. You can:

  1. Type (or copy and paste) the code directly into the language's interpreter;
  2. Write and run the code in the IDE of your choice;
  3. Write the code using a text editor and run the created file in the interpreter.

The examples are the same adopted for JavaScript. Therefore, you can compare languages, and notice similarities and differences between them.

Getting to Know Prolog Through Experimentation

Examples of use and outputs of code snippets described in this section using the `swipl` interpreter for Prolog on the command line.
  1. Text writing:

    main :-
        writeln("One line."),
        writeln("Another line."),
        writeln("One line.\nAnother line.").

    If you are using Prolog in REPL, you must not use main. If the code snippets to do define variables, you can evaluate the implementation line by line in a REPL. For instance: writeln("One line."). You should remember the dot is important.

    It is also possible to evaluate all lines separated by commands at once, provided that the last line ends with a dot.

  2. Comments (text that is ignored by the interpreter; documentation):

    main :-
        writeln("Interpreter processes"). % Interpreter ignores.
    /* <- Here the comment starts.
    It can spawn multiple lines.
    Here it ends -> */
    /* It can also start and end in the same line. */
    % Though, for single line comments, it is easier to use this comment style.
  3. Mathematics operations:

    main :-
        A is 1 + 1, writeln(A),
        B is 2 - 2, writeln(B),
        C is 3 * 3, writeln(C),
        D is 4 / 4, writeln(D). % What does happen if you try to divide by 0? Try it!
    • Math expressions:

    main :-
        X is 1 + 2 - 3 + (4 * 5) / 6,
        writeln(X).

    main :-
        X is 5 ** 2,
        writeln(X).

    main :-
        X is sqrt(25),
        writeln(X).
    • Trigonometric functions, such as sin (documentation: sin() and pi):

    main :-
        X is sin(pi / 2.0), % Sin.
        writeln(X).
  4. Comparisons (result in true or yes mean true; false or no means false):

    write_result(X) :- X, writeln("True").
    write_result(X) :- not(X), writeln("False").
    
    main :-
        write_result(1 =:= 2), % Equal: both equals are required!
        write_result(1 =\= 2). % Different: both equals are required!
    write_result(X) :- X, writeln("True").
    write_result(X) :- not(X), writeln("False").
    
    main :-
        write_result("Franco" == "Franco"),
        write_result("Franco" \= "Franco"),
        write_result("Franco" \= "Seu Nome"),
        % Prolog differs lower case characters from upper case ones (and vice-versa).
        write_result("F" =:= "f"), % You also could use ==
        write_result("F" =\= "f"), % You also could use \=
        write_result("Franco" == "franco"),
        write_result("Franco" \= "franco").
    write_result(X) :- X, writeln("True").
    write_result(X) :- not(X), writeln("False").
    
    main :-
        write_result(1 < 2), % Less than.
        write_result(1 > 2), % Greater than.
        write_result(1 =< 2), % Less or equal than.
        write_result(1 >= 2). % Greater or equal than.
  5. Variables and assignment (documentation):

    Variables are like boxes that store values put inside them. In Prolog, variables always should start with an upper case letter. Furthermore, there is no attribution, but a process called unification.

    main :-
        X = 123,
        writeln(X).

    For Mathematics, you normally should use is instead of =. Otherwise, Prolog will unify the expression instead of calculating its results.

    main :-
        Expression = 123.456 + 987.654,
        writeln(Expression),
        Result is 123.456 + 987.654,
        writeln(Result).

    Unlike other languages, a variable cannot be changed after unification. To unify a variable with a new value, you need to create a new variable.

    main :-
        Name1 = "Franco",
        writeln(Name1),
        Name2 = "Franco Garcia",
        writeln(Name2).
    main :-
        A = "Franco",
        writeln(A),
        B = "Your Name",
        writeln(B),
        C = "Other Name",
        writeln(C).

    The language does not provide logical values, either. As an alternative, you can define symbols or facts (started with lower case).

    true_or_false(Expression, Result) :- Expression, Result = true.
    true_or_false(Expression, false) :- not(Expression).
        % The false in the second parameter is equivalent to declaring Resulte and unify
        % Result = false.
    
    main :-
        LogicalValue1 = true,
        writeln(LogicalValue1),
        LogicalValue2 = false,
        writeln(LogicalValue2),
        X is 1 + 1,
        true_or_false(X == 2, Y),
        writeln(Y).
  6. Constants (documentation):

    SWI Prolog does not allow creating constants (though other implementations may). In reality, there exists some constants such as pi, though the idiomatic alternative is to create a predicate providing the value.

    pi(3.14159).
    
    main :-
        pi(X),
        writeln(X).
    e(2.71828).
    
    main :-
        e(X),
        writeln(X),
        X = 0. % main will fail, because it is not possible to modify a previously unified variable.
  7. Errors:

    main :-
        writeln(Ooops!), % Text should be between double quotes.
        writel("Incorret name for writeln"),
        X is 1 / 0,
        writeln(X),
        Y is 0 / 0,
        writeln(Y).
  8. Strings for words and text (documentation):

    main :-
        writeln("Ok, this is a valid string"),
        writeln("Ok, this is a valid string"),
        writeln("Ok, this is also a valid string").
    main :-
        writeln("Para 'misturar' aspas, use diferentes das externas."),
        writeln("Caso contrário, você precisa escapá-las com uma contrabarra, assim: \". A contrabarra é necessária.").
  9. Logical operators (documentation):

    Prolog does not define logical operations. However, it is possible to define them using predicates (or using a library, such as the one in this link to the documentation).

    % Operand1 and Operand2 = Result
    % Operand1     Operand2   Result
    and(false,     false,     false).
    and(false,     true,      false).
    and(true,      false,     false).
    and(true,      true,      true).
    
    % Operand1  or Operand2 = Result
    % Operand1     Operand2   Result
    or(false,      false,     false).
    or(false,      true,      true).
    or(true,       false,     true).
    or(true,       true,      true).
    
    % not Operand1 = Result
    % Operand1       Result
    not(false,       true).
    not(true,        false).
    
    main :-
        and(true, true, X), % This is a logical "and".
        writeln(X),
        or(true, false, Y), % This is a logical "or".
        writeln(Y),
        not(true, Z), % This is a logical "not".
        writeln(Z).
  1. Conditions (documentation):

    browser_name("Firefox") :- writeln("Mozilla Firefox").
    
    main :-
        Browser = "Firefox",
        browser_name(Browser).
    browser_name("Firefox") :- writeln("You use a browser by Mozilla"), !.
    browser_name(_) :- writeln("You use another browser.").
    
    main :-
        MyBrowser = "Your Browser",
        browser_name(MyBrowser).
    browser_name("firefox") :- writeln("You use a browser by Mozilla"), !.
    browser_name("chrome") :- writeln("You use a browser by Google"), !.
    browser_name("chromium") :- writeln("You use a browser by Google"), !.
    browser_name("edge") :- writeln("You use a browser by Microsoft"), !.
    browser_name("safari") :- writeln("You use a browser by Apple"), !.
    browser_name("internet explorer") :- writeln("You should use a more modern browser..."), !.
    browser_name(_) :- writeln("You use another browser.").
    
    main :-
        IUse = "X",
        string_lower(IUse, IUseLowerCase),
        browser_name(IUseLowerCase).
  2. Loops (documentation):

    for(End, End).
    for(I, End) :-
        I < End,
        format("~d\n", I),
        NextI is I + 1,
        for(NextI, End).
    
    main :-
        for(0, 5).
    while(End, End).
    while(J, End) :-
        J < End,
        format("~d\n", J),
        NextJ is J + 1,
        while(NextJ, End).
    
    main :-
        while(0, 5).
    repeat(End, End).
    repeat(I, End) :-
        format("~d\n", I),
        I < End,
        NextI is I + 1,
        repeat(NextI, End).
    
    main :-
        repeat(0, 5).
  3. Functions (documentation):

    Instead of functions, Prolog provides predicates. Predicates have been used in previous examples. They allow defining code corresponding to functions in other programming languages, though they also allow defining relations for symbolic processing.

    my_function(X, Y, Result) :- Result is X + Y.
    
    main :-
        % A function is a block of code that performs arbitrary processing as defined
        % by the programmer.
        % After the definition, you can execute the function whenever wanted, using
        % a function call.
        my_function(12, -34, Z1), % This is an example of a function call.
        writeln(Z1),
        my_function(1, 2, Z2),
        writeln(Z2). % This is another example.
  4. Data types (documentation):

    main :-
        IntegerNumber = 1,
        AnotherIntegerNumber = -1,
        RealNumber = 1.23,
        LogicValue = true, % or false; you can adopt a convention of two values.
        StringForText = "Text here. Line breaks use\nthat is, this will be at\n the third line.".
  5. Input (documentation: read_line_to_string(), number_string(), and string_concat()):

    :- use_module(library(readutil)).
    
    main :-
        % Once there is a request for a value, type one then press `enter`.
        writeln("What is your name? "),
        read_line_to_string(user_input, YourName),
        writeln("How old are you? "),
        read_line_to_string(user_input, YourAgeText),
        % number_string() converts a number in text format to a whole number.
        number_string(YourAge, YourAgeText),
        writeln(YourName),
        writeln(YourAge),
        % The function string_concat() performs an operation called
        % concatenation that combines the second string after the first.
        string_concat("Hello, ", YourName, Hello1),
        string_concat(Hello1, "!", Hello2),
        writeln(Hello2),
        format("You are ~d years old.\n", YourAge).

Congratulations! You Are Already Able to Write Any Program in Prolog

Don't you believe it? You can find the explanation in the introduction to JavaScript

In short, it is not enough to learn the syntax of a language to solve problems using it. It is much more important learning programming logic and developing computational thinking skills than learning the syntax of a programming language. In fact, when you are in doubt about the syntax, you just have to consult the documentation. You do not have to memorize it.

After you learn a first programming language, it is relatively simple to learn other languages (that adopt similar programming paradigms to the first one). To verify this statement, you can open a new window in your browser and place it side by side with this one. Then, you can compare the source code blocks written in Prolog (in this window) and in Python (in the second window).

If you wish to perform comparisons with other programming languages, the following options are available:

Next Steps

Once the development environment is configured, you can continue your system development journey.

To avoid repetitions, I recommend reading the page about configuring the JavaScript environment. Even if you are not interested at the language, many discussions are relevant to any programming language. Besides, you will understand a way to create Internet pages and will be able to create content for your browser.

Until GDScript (for Godot Engine), the topics describe develoment environment configurations for a few programming languages. After GDScript, the focus becomes basic concepts for learning programming.

  • Informatics
  • Programming
  • Beginner
  • Dev Env
  • Windows
  • Linux
  • Prolog