Functions in Prolog

Functions are central in Prolog. We’ll learn about functions (also known as predicates in Prolog) with a few different examples.

% Here's a predicate that takes two integers and returns their sum.
plus(A, B, Sum) :-
    Sum is A + B.

% In Prolog, we don't need to specify types. The language is dynamically typed.
% Here's a predicate that sums three numbers.
plus_plus(A, B, C, Sum) :-
    Sum is A + B + C.

% The main predicate serves as the entry point of our program.
main :-
    % Call a predicate using its name and providing arguments.
    plus(1, 2, Result1),
    format('1+2 = ~w~n', [Result1]),

    plus_plus(1, 2, 3, Result2),
    format('1+2+3 = ~w~n', [Result2]).

% To run the program, we need to query the main predicate.
:- main.

To run this Prolog program, you would typically save it in a file (e.g., functions.pl) and then consult it in a Prolog interpreter:

$ swipl -s functions.pl
1+2 = 3
1+2+3 = 6

In Prolog, we define predicates instead of functions. Predicates in Prolog are relations between their arguments, rather than functions that return values. However, we can use them to achieve similar results.

The is operator in Prolog is used for arithmetic evaluation. It calculates the expression on its right side and unifies the result with the variable on its left side.

Prolog uses pattern matching and backtracking to solve goals, which is quite different from imperative languages. This example demonstrates basic arithmetic operations and output formatting in Prolog.

There are several other features to Prolog predicates. One is the ability to have multiple solutions, which we’ll look at in future examples.