next up previous contents
Next: Prolog execution as the Up: Prolog as a Procedural Previous: Assign-once Variables

Nondeterminism

Pascal is a deterministic programming language (as are C and Algol); at any point in the execution of a Pascal program there is exactly one next step. Prolog, however, is nondeterministic. There are points in the execution of a Prolog program when there are multiple legal next steps. The way this is specified in Prolog is to give multiple definitions of the same procedure. For example, we could write a procedure to find both square roots of a positive real number by:

    a_sqrt(X,Y) :-
        X > 0,
        Y is sqrt(X).
    a_sqrt(X,Y) :-
        X > 0,
        Y is -sqrt(X).
A_sqrt takes a number and returns its square root. Here we want it to return both square roots, one positive and one negative. We can do that by giving two definitions of a procedure a_sqrt. A Pascal compiler would complain that the procedure is multiply defined, but Prolog accepts such multiple procedure definitions happily. The first definition checks that the input argument is greater than 0, and if so uses a Prolog primitive builtin to calculate the positive square root. The second definition does the same, but returns the negation of the positive square root. In Prolog terminology, each definition is called a ``clause'', so a_sqrt is defined by two clauses.



 
next up previous contents
Next: Prolog execution as the Up: Prolog as a Procedural Previous: Assign-once Variables
David S. Warren
1999-07-31