Values in Prolog

Our first example will demonstrate various value types in Prolog including atoms, numbers, and boolean expressions. Here’s the full source code:

main :-
    % Atoms, which can be concatenated using the atom_concat/3 predicate.
    atom_concat('pro', 'log', X),
    writeln(X),

    % Integers and floats.
    Y is 1 + 1,
    format('1+1 = ~w~n', [Y]),
    Z is 7.0 / 3.0,
    format('7.0/3.0 = ~w~n', [Z]),

    % Boolean expressions.
    (true, false -> writeln(true) ; writeln(false)),
    (true; false -> writeln(true)),
    (\+ true -> writeln(true) ; writeln(false)).

To run the program, save the code in a file (e.g., values.pl) and use a Prolog interpreter:

$ swipl -q -f values.pl -t main
prolog
1+1 = 2
7.0/3.0 = 2.3333333333333335
false
true
false

Let’s break down the example:

  1. Atoms: In Prolog, atoms are similar to strings in other languages. We use the atom_concat/3 predicate to concatenate two atoms.

  2. Numbers: Prolog supports both integers and floating-point numbers. Arithmetic operations are performed using the is operator.

  3. Boolean expressions: Prolog uses , for logical AND, ; for logical OR, and \+ for logical NOT. The -> operator is used for if-then-else constructs.

  4. Output: We use writeln/1 for simple output and format/2 for formatted output.

Note that Prolog is a logic programming language, so the syntax and concepts differ significantly from imperative languages. The main/0 predicate serves as the entry point of our program.