These are the notes for the Prolog language part of the Computational Logic course. The slides and notes go essentially in sync, with these notes providing the explanations, reasoning, and some side comments.
How to use this interactive document:
The code boxes can be edited and run in place. Feel free to edit any program and make all the queries you want!
Prolog is a real, practical programming language based on that paradigm — the most popular one, and standardized by ISO. What does it add?
A fixed control. By default the search rule is depth-first and the computation rule is left-to-right. We no longer choose; the language has chosen for us. That is a loss of generality, and it buys a great deal: a program with a fixed, known execution order can be compiled into fast code — including native code — and then it runs at roughly the speed of any other language.
A large library of built-in predicates. Some declarative, some not — but all of them efficient. Arithmetic is the obvious case: built-in integer arithmetic is enormously faster than the Peano arithmetic we wrote in the previous part.
Things that go beyond first-order logic. Higher-order predicates; meta-logical predicates, which can ask whether something is still a variable — a question that cannot even be stated in pure logic; and modification of the program itself while it runs: programs that rewrite themselves as they go.
A program without search — one clause per procedure, or several clauses of which only one ever matches a given call, so the clauses work like a case statement rather than as alternatives — runs, under the left-to-right rule, exactly like its imperative or strict functional counterpart. Which means any imperative or functional program can be transliterated into Prolog and will behave the same way. The one adjustment is that a variable cannot be overwritten; but we just use a fresh one, and real systems offer imperative assignment anyway.
A program with search — at least one predicate where more than one clause matches — has no direct counterpart in imperative or functional programming. (List comprehensions are the nearest thing.)
And which of the two we have depends on the call mode. append/3 given two lists behaves exactly like an imperative concat; given the third list it becomes a search. Same program.
That list is also the plan of this part of the course.
The fixed control described above is already most of the difference between Prolog and pure logic programming — at least for pure Prolog programs, where the differences are that execution is depth-first and that this lets us control the search. Everything below is what the ISO standard adds on top. Other systems have plenty more, but those extensions are system-specific; the standard is what everyone agrees on.
For the system used in this course, see the separate part on Developing Programs with a Logic Programming System.
There are some new data types.
Numbers — real numbers now, not Peano numbers: 0, 999, -77, 5.23, 0.23e-5, 0.23E-5. And a very nice property of many current systems, Ciao among them: integers have infinite precision. There is no word size, and no overflow.
?- X is 1234567890123456789012345678901234567890 * 987654321.Expected answer:
X = 1219326311248285321124828532112482853211126352690 ?Strings are just lists of character codes (ASCII, and also, e.g., UTF-8 codes). "foo" is the list of the codes of f, o and o:
?- X = "foo".Expected answer:
X = [102,111,111] ?Which is honest, but not very readable. There is a Prolog flag for it — flags are parameters of the system that can be changed at will — and this one is worth remembering:
?- set_prolog_flag(write_strings, on), X = "foo".Expected answer:
X = "foo" ?Now, when the system prints a list of numbers that all happen to be printable character codes, it prints it as a string. A list that does not start with such codes is printed as a list, as before. The flag stays on until it is switched off again, which we do here so that the answers below are printed as lists until we say otherwise:
?- set_prolog_flag(write_strings, off).Expected answer:
yesComments are % to the end of the line, or /* ... */ as in C.
The declaration is
:- op(<precedence>, <type>, <operator(s)>).Precedence is an integer from 1 to 1200. The general rule: the operator with the highest precedence number is the principal functor. So if + has a higher precedence number than /, then a+b/c is a+(b/c), that is, +(a,/(b,c)). Note that some other languages number precedence the other way around. And parentheses always work: /(+(a,b),c) is (a+b)/c.
Type is one of nine mnemonics, and they read as pictures — f is the operator, x and y are the arguments:
Operators is a single atom or a list of atoms.
?- write_canonical(1+2/4^2), nl.Expected answer:
+(1,/(2,^(4,2))) yesSo 4^2 first, then 2 divided by that, then 1 plus all of it — as expected, but now we know.
| standard notation | operator notation |
|---|---|
| +(a,/(b,c)) | a+b/c |
| is(X, mod(34, 7)) | X is 34 mod 7 |
| <(+(3,4),8) | 3+4 < 8 |
| =(X,f(Y)) | X = f(Y) |
| -(3) | -3 |
| spy(/(foo,3)) | spy foo/3 |
| :-(p(X),q(Y)) | p(X) :- q(Y) |
| :-(p(X),','(q(Y),r(Z))) | p(X) :- q(Y),r(Z) |
Look at the last two lines. A clause is a term: the principal functor is :-, the neck; the first argument is the head; the second is the body, which for a conjunction is the term ','(q(Y),r(Z)) — nested to the right, exactly like the dots of a list.
That is why assert/1 — add a clause to the running program — will be a one-liner later on: we build a term and hand it over. Nothing has to be converted.
One syntactic trap. Parentheses must be used around operators whose priority is higher than 1000, the priority of the comma. So we write ..., assert( (p :- q) ), ... — without the inner parentheses the argument is read only up to the :-, and we get a syntax error.
:- module(_,_,[]). % v------- Infix operator, no associativity :- op(500,xfx,is_father_of). % ^---- Precedence = 500then these two facts:
% is_father_of(john, peter). % is_father_of(peter,jim).can be written the way we would say them out loud:
john is_father_of peter. peter is_father_of jim.The operator changes only how the term is written and read. Internally the fact is still is_father_of(john,peter), as a query in the ordinary notation shows:
?- is_father_of(X,Y).Expected answer:
X = john, Y = peter ? ; X = peter, Y = jim ? ; no
?- op(500,xfx,is_father_of).Expected answer:
yesand now we can ask:
?- X is_father_of Y.Expected answer:
X = john, Y = peter ? ; X = peter, Y = jim ? ; noWhy the locality? Because operators are how language extensions are defined. One module can use functional syntax, another can use an imperative syntax, and neither disturbs the other. Without locality they could not be combined.
(A file that starts with the traditional two-argument declaration, :- module(_,_)., behaves as in classical Prolog systems: its operators are also made visible at the top level when it is loaded. The file above starts with :- module(_,_,[])., so its operator stays inside.)
Operators also let us design a notation of our own for the data. For example, these facts are instructions of an assembly language (just the syntax):
:- op(1100,fx,[load,mult,bne]).
:- op( 500,fx,@).
:- op(1200,xfx,:).
label1 : load @r3,r1.
load 5,r2.
mult r1,r2.
bne 0,label1.They are still ordinary facts: with those declarations, load 5,r2. is read as load((5,r2)):?- load(X).Expected answer:
X = (5,r2) ?
:- op( 1200, xfx, [ :-, --> ]).
:- op( 1200, fx, [ :-, ?- ]).
:- op( 1150, fx, [ dynamic, multifile, meta_predicate]).
:- op( 1100, xfy, [ ; ]).
:- op( 1050, xfy, [ -> ]).
:- op( 1000, xfy, [ ',' ]).
:- op( 900, fy, [ \+, spy, nospy ]).
:- op( 700, xfx, [ =, \=, is, =.., ==, \==, @<, @>, @=<,
@>=, =:=, =\=, <, >, =<, >= ]).
:- op( 550, xfx, [ : ]).
:- op( 500, yfx, [ +, -, #, /\, \/ ]).
:- op( 400, yfx, [ *, /, //, rem, mod, <<, >> ]).
:- op( 200, fy, [ +, -, \ ]).
:- op( 200, xfx, [ ** ]).
:- op( 200, xfy, [ ^ ]).Read it as a map. It tells us where a new operator can be slotted in: above or below the clause neck, the comma, the disjunction, the implication, unification, the arithmetic comparisons, the arithmetic operators.
:- module(_, _).
grandparent(C,G) :-
parent(C,P),
parent(P,G).
parent(C,P) :-
father(C,P).
parent(C,P) :-
mother(C,P).
father(charles, philip).
father(ana, george).
mother(charles, ana).?- grandparent(charles,X).Expected answer:
X = george ?Follow it on the tree: parent(charles,P) first tries father, giving P = philip; then parent(philip,G) has no solution at all, and the whole branch fails. Backtracking returns to the last choice point, takes mother(charles,ana), and parent(ana,G) then succeeds with george.
We can do it right here. The box below is a small playground of its own, with a copy of the program on the left and a top level on the right (the programs and the queries of the rest of this page do not reach it). Press its debug button (🐞), type grandparent(charles,X). at the ?- prompt on the right, press Enter, and then press Creep (or Enter) repeatedly. Each step prints the goal and what is happening to it (Call, Exit, Fail or Redo), and marks that goal in the program:
:- module(family,_).
%! \begin{miniplayground}
grandparent(C,G) :-
parent(C,P),
parent(P,G).
parent(C,P) :-
father(C,P).
parent(C,P) :-
mother(C,P).
father(charles, philip).
father(ana, george).
mother(charles, ana).
%! \end{miniplayground}In twenty steps we see all of it: father(charles,P) exits with philip; the two clauses of parent(philip,G) fail; parent(charles,P) is entered again (Redo) and exits with ana, through mother/2; and parent(ana,G) exits with george. (The other buttons that appear while stepping are Skip, which runs the current call to its end without showing its steps, Leap, which continues without stopping, Retry and Fail. Pressing the debug button again turns the debugger off.)The type of arithmetic terms. It is defined exactly the way we defined types in the pure part:
The type itself is worth looking at as a type: a long but perfectly ordinary recursive definition, in the same shape as nat/1 or list/1, where every alternative but the first is built from smaller arithmetic expressions. Its real name in Ciao is arithexpression/1; we write arithexpr below for short.
arithexpr := | num | + arithexpr | - arithexpr | ++ arithexpr | -- arithexpr | arithexpr + arithexpr | arithexpr - arithexpr | arithexpr * arithexpr | arithexpr // arithexpr | arithexpr / arithexpr | abs(arithexpr) | sign(arithexpr) | float_integer_part(arithexpr) | float(arithexpr) | float_fractional_part(arithexpr) | arithexpr ** arithexpr| exp(arithexpr) | log(arithexpr) | sqrt(arithexpr) | sin(arithexpr) | cos(arithexpr) | atan(arithexpr) | [arithexpr] | ...num is the base case — a number is an arithmetic term — and [arithexpr] is the one that looks odd until we remember that "a" is a list of character codes: a one-element list evaluates to its element, which is how X is "a" gives 97.
Beyond those there are rem, mod, gcd, the shifts and the bitwise operators, and integer, truncate, floor, round, ceiling. The manuals have the complete list.
?- X = 3+4/2, write_canonical(X), nl.Expected answer:
+(3,/(4,2)) X = 3+4/2 ?X is bound to a data structure. Nothing was computed.
The two things that can be done with an arithmetic term are evaluating it and comparing it.
Z is X evaluates X — which must be an arithmetic term — and unifies the result with Z. The comparison operators <, >, =<, >=, =:= (arithmetic equality) and =\= (arithmetic inequality) evaluate both arguments and compare the results.
?- X is 3*3//2.Expected answer:
X = 4 ?
?- Z = 3//2, X is 3+Z.Expected answer:
X = 4, Z = 3//2 ?Look carefully at that second one. Z is bound to the term 3//2 — not to 1. The evaluation happens only at the is, and at that moment the whole structure 3+Z is evaluated, Z and all:
?- X = 1 + Y, Y = 3/2, Z is X.Expected answer:
X = 1+3/2, Y = 3/2, Z = 2.5 ?Y is not 1.5 and is not a rational number; it is the term /(3,2). is/2 interprets the structure handed to it, and only then does arithmetic happen.
Failure — the goal is well formed, evaluates fine, and simply is not true. The system backtracks as usual:
?- X=3, Y=4, Y < X+1.Expected answer:
no
?- X=3, Y=4, X is Y+1.Expected answer:
no
?- X=3, Y=4, X =:= Y.Expected answer:
noError — the goal cannot be evaluated at all, and execution is aborted:
?- Y=4, Y < a+1.Expected answer:
{ERROR: arithmetic:is/2, arg 2 - expected an arithmetically evaluable expression, found /(a,0)}Read that message; it is a good one. The predicate is is/2 (which stands in for all the arithmetic operators) in module arithmetic; the problem is in argument 2; it expected something evaluable and found a — printed in name/arity form as /(a,0), i.e., the atom a.?- X is Z+1.Expected answer:
{ERROR: arithmetic:is/2, arg 2 - argument is not sufficiently instantiated}An unbound variable has no value, so there is nothing to evaluate (?- X is 3+Y. ends in the same way). Note that the pure version would have worked perfectly: plus(Z,s(0),Y) is reversible and would have generated candidates. is/2 cannot, because it is a function.?- X=3, X =:= f(a).Expected answer:
{ERROR: arithmetic:=:=/2, arg 2 - expected an arithmetically evaluable expression, found /(f,1)}So Peano arithmetic was declarative but slow; is/2 is fast but not declarative; constraints are both. That is the subject of the part of the course on constraint logic programming, and one of the things constraints do is give arithmetic its declarativeness back.
plus(X,Y,Z) :- Z is X + Y.but it works in one mode only: X and Y must be bound to arithmetic terms. We have lost the recursive structure of the numbers, and with it reversibility. (The meta-logical predicates and the constraints that come later let us use arithmetic in more modes again.) What we have won in exchange is a great deal of performance.
Factorial makes the trade visible. Here is the version that uses Peano arithmetic:
:- module(_,_).
peano_factorial(0,s(0)).
peano_factorial(s(N),F) :-
peano_factorial(N,F1),
peano_times(s(N),F1,F).
peano_times(0,_,0).
peano_times(s(X),Y,Z) :-
peano_times(X,Y,W),
peano_plus(W,Y,Z).
peano_plus(0,Y,Y) :-
nat(Y).
peano_plus(s(X),Y,s(Z)) :-
peano_plus(X,Y,Z).
nat(0).
nat(s(X)) :- nat(X).?- peano_factorial(s(s(s(s(s(0))))),F).Expected answer:
F = s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(0)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) ?That is the number 120, and the size of the answers is the problem. In the next queries we use _ for the result, so that it is computed but not printed:
?- peano_factorial(s(s(s(s(s(s(0)))))),_).Expected answer:
yes
?- peano_factorial(s(s(s(s(s(s(s(0))))))),_).Expected answer:
yes
?- peano_factorial(s(s(s(s(s(s(s(s(s(s(0)))))))))),_).Expected answer:
yesUp to 7 or 8 the answer is immediate, but each step multiplies the work by more than ten: run directly in Ciao on a laptop, the factorial of 9 takes about 0.05 seconds, that of 10 (the last query) about 0.7 seconds, and that of 11 about 20 seconds and 2 GB of memory — to build a term with almost forty million nested s. (The factorial of 11 is too much for the system when it runs in the browser, as in this page.)
And this is the same algorithm using the ISO-Prolog built-ins is/2 and >/2:
factorial(0,1).
factorial(N,F) :-
N > 0,
N1 is N-1,
factorial(N1,F1),
F is F1*N.?- factorial(7,F).Expected answer:
F = 5040 ?Instantaneous — and so is the next one, whose answer has 2568 digits:
?- factorial(1000,F).Expected answer (only the first 60 digits are shown here):
F = 402387260077093773543702433923003985719374864210714632543799... ?Imagine that number built out of nested s/1 terms; the Peano version could never compute it. (The factorial of 100000, ?- factorial(100000,_)., also finishes when run directly in Ciao; it takes about twelve seconds.)
wrong_factorial(0,1).
wrong_factorial(N,F) :-
N > 0,
N1 is N-1,
F is F1*N,
wrong_factorial(N1,F1).?- wrong_factorial(3,F).Expected answer:
{ERROR: arithmetic:is/2, arg 2 - argument is not sufficiently instantiated}At the moment F is F1*N is reached, F1 is a fresh variable — the recursive call that will bind it has not run yet. In pure logic programming this would have been survivable: the pure times/3 would have generated candidates and the recursive call would have checked them, inefficiently but correctly. is/2 cannot do that.The same reason kills the reverse direction:
?- factorial(N,6).Expected answer:
{ERROR: arithmetic:>/2, arg 1 - argument is not sufficiently instantiated}factorial/2 with the built-in arithmetic is a function, not a relation. The way to make it tail recursive without errors is an accumulating parameter, which is the subject of the following exercise.They are unary relations that check the type of a term:
They behave as if defined by a (possibly infinite) table of facts — integer(1). integer(2). … — and they either succeed or fail; they never raise an error.
That behavior is outside first-order logic, because what it really tests is the instantiation state of a variable — a question that cannot even be phrased in logic.
?- integer(1).Expected answer:
yes
?- integer(1.0).Expected answer:
no
?- integer(X).Expected answer:
no
?- X = 1, integer(X).Expected answer:
X = 1 ?
?- integer(X), X = 1.Expected answer:
noTwo orders, two different answers — so integer/1 is not a pure predicate. Contrast nat/1: X = s(s(s(0))), nat(X) and nat(X), X = s(s(s(0))) both succeed. The second one has to backtrack through 0, s(0), s(s(0)) before it gets there — less efficient, but logically consistent, which is the whole point.
Is integer/1 therefore wrong? No — it is impure, and we have to know it. For a pure integer test there are Peano numbers, or constraints. A part of a program that uses these built-in tests can no longer be read as logic; it has to be read as an imperative program.
:- module(_,_). plus_plain(X,Y,Z) :- Z is X + Y.
?- plus_plain(4,5,Z).Expected answer:
Z = 9 ?It works, but it cannot run backwards:
?- plus_plain(X,5,9).Expected answer:
{ERROR: arithmetic:is/2, arg 2 - argument is not sufficiently instantiated}If we guard the clauses with number/1 we can cover three modes instead of one:plus(X,Y,Z) :- number(X),number(Y), Z is X + Y. plus(X,Y,Z) :- number(X),number(Z), Y is Z - X. plus(X,Y,Z) :- number(Y),number(Z), X is Z - Y.
?- plus(4,5,Z).Expected answer:
Z = 9 ?
?- plus(X,5,9).Expected answer:
X = 4 ?Give it any two of the three and it computes the third. But partitioning a number into two others is beyond it:
?- plus(X,Y,9).Expected answer:
no
The honest answer, of course, is neither no nor an error: it is the equation X = 9-Y. That is exactly what a constraint system answers, and if Y = 2 is added later the equation resolves itself. Handling enough cases here by hand amounts to writing a small part of constraint logic programming ourselves. Constraints are the real solution, and they have their own part of the course.
?- functor(t(b,a),F,A).Expected answer:
A = 2, F = t ?
?- functor(Term,f,3).Expected answer:
Term = f(_,_,_) ??- functor(Vector,v,100). builds a hundred-argument term in one step — which is the beginning of an array. (In some systems the arity is limited to 256 by default; there are libraries for unbounded arrays.)
?- _T=date(9,'February',1947), arg(3,_T,X).Expected answer:
X = 1947 ?(The _ at the beginning of _T tells the top level not to print the value of that variable.) The same result comes from plain unification:
?- _T=date(9,'February',1947), _T=date(_,_,X).Expected answer:
X = 1947 ?and where the shape is fixed and known that is the better style. arg/3 earns its keep when the position is computed, as in the array code below.
Building and filling in one go:
?- functor(Array,array,5), arg(1,Array,black), arg(5,Array,white).Expected answer:
Array = array(black,_,_,_,white) ?
?- arg(2, [a,b,c,d], X).Expected answer:
X = [b,c,d] ?Not b. Because a list is not a special data type: [a,b,c,d] is the term '.'(a,[b,c,d]), a binary structure whose second argument is the tail. It can be confirmed directly with functor([a,b,c,d],F,A), which answers F = '.', A = 2.
:- module(_,_).
% Example of Structure Inspection: Arrays
add_arrays(A,B,C):-
functor(A,array,N), % Gets length N from array A
functor(B,array,N), % Checks that array B is of same length
functor(C,array,N), % Creates an array C to hold the result
add_elements(N,A,B,C).
add_elements(0,_A,_B,_C).
add_elements(I,A,B,C):-
I>0,
arg(I,A,AI),
arg(I,B,BI),
arg(I,C,CI),
CI is AI + BI,
I1 is I - 1,
add_elements(I1,A,B,C).?- add_arrays(array(1,2,3),array(4,5,6),R).Expected answer:
R = array(5,7,9) ?Note the elegance of the length check: writing the same N in all three functor/3 calls reads the length off A, checks that B has it, and creates C with it. Let us walk through it once (stepping through it in the debugger is a good way of seeing it), running forwards with the first two arrays given:
This is what unification buys: a formal theory that provides these memory operations directly, with no need to model the memory ourselves.
Note also that in the recursive call the three arrays are passed unchanged — the same pointers go around every time. It is the index that moves.
All of this can be watched in the debugger. The box below is a small playground with a copy of the program. Press its debug button (🐞), type add_arrays(array(1,2,3),array(4,5,6),R). at the ?- prompt on the right, and step with Creep (or Enter):
:- module(arr,_).
%! \begin{miniplayground}
add_arrays(A,B,C):-
functor(A,array,N),
functor(B,array,N),
functor(C,array,N),
add_elements(N,A,B,C).
add_elements(0,_A,_B,_C).
add_elements(I,A,B,C):-
I>0,
arg(I,A,AI),
arg(I,B,BI),
arg(I,C,CI),
CI is AI + BI,
I1 is I - 1,
add_elements(I1,A,B,C).
%! \end{miniplayground}The built-ins appear in the trace with the name of their module in front (term_basic:functor, term_basic:arg, arithmetic:is), and the variables are printed with numbers, such as _34160. Three moments are worth watching:The third argument can also be given, and then the sum is checked:
?- add_arrays(array(1,2,3),array(4,5,6),array(5,7,9)).Expected answer:
yesMismatched lengths simply fail:
?- add_arrays(array(1,2,3),array(4,5),R).Expected answer:
noAn alternative is to use lists instead of structures:
add_lists([],[],[]).
add_lists([X|Xs],[Y|Ys],[Z|Zs]):-
Z is X + Y,
add_lists(Xs,Ys,Zs).?- add_lists([1,2,3],[4,5,6],R).Expected answer:
R = [5,7,9] ?
?- add_lists([1,2,3],[4,5,6],[5,7,9]).Expected answer:
yes
?- add_lists([1,2,3],[4,5],R).Expected answer:
no
Which version is better? The list one is shorter and easier to write — a recursion is a more natural way to express this than a loop, and a loop always needs an extra variable that has nothing to do with the problem. The array version wins when random access is needed: jump to the first element, then the last, then back — arg/3 does that in constant time and a list does not.
There is one thing to be said for the verbose loop, though: we can see exactly what it does. In an imperative language it is not always obvious whether the test happens before or after the body, or where the decrement lands. Here all of it is written out in front of us.
?- add_arrays(array(1,2,3),A2,array(5,7,9)).Expected answer:
{ERROR: arithmetic:is/2, arg 2 - argument is not sufficiently instantiated}By the time the loop reaches CI is AI + BI we are giving CI and AI and asking for BI, and is/2 cannot run backwards. The fix is the one we have just seen: replace is/2 with the guarded plus/3, and array subtraction starts working too.What it still will not do is take one array and enumerate all the pairs of arrays that add up to it. That needs Peano arithmetic — which we could write — or a constraint, which is reversible arithmetic and runs in every direction.
:- module(_,_). % Example of Structure Inspection: Arrays, with some syntax :- use_package(fsyntax).make @ an infix operator:
:- op(250,xfx,@).define @ as a call to arg/3:
T @ N := A :- arg(N,T,A).
% Same as: @(T,N) := A :- arg(N,T,A).
% or also: @(T,N,A) :- arg(N,T,A).turn on the evaluation of all occurrences of @/2::- fun_eval @ / 2.define array/2, to hide the call to functor/3:
array(A,N) :- functor(A,array,N).and turn on the evaluation of arithmetic expressions (such as I-1):
:- fun_eval arith(true).Now array addition can be defined as:
add_arr(A,B,C) :-
array(A,N),
array(B,N),
array(C,N),
add_els(N,A,B,C).
add_els(0,_,_,_).
add_els(I,A,B,C) :-
I>0,
C@I is A@I + B@I, % <- Using our definition of @/2
add_els(I-1,A,B,C).?- add_arr( array(1,2,3), array(4,5,6), R).Expected answer:
R = array(5,7,9) ?
?- add_arr( array(1,2,3), array(4,5,6), array(5,7,9)).Expected answer:
yes
?- add_arr( array(1,2,3), array(4,5),R).Expected answer:
no(That last one fails; raising an error would be even better.)
C@I is A@I + B@I is what we wanted to write in the first place. The point is not the convenience; it is that the notation was added by the user, with an operator declaration and one clause, and the rest of the language did not have to know about it.
And nothing forces @. We could declare sub as an operator and write a sub 3. Declared as yfx, the operator can even be chained: with :- op(250,yfx,@)., the expression M@3@2 is element 2 of row 3 of a matrix M written as an array of arrays. The syntax is extensible, and we decide how convenient we want it to be.
:- module(_, _, [functional,loops,arrays]).
:- use_module(library(arrays/arrays_log)).
primes(N) := Res :-
% Initialize the array with n+1 values to access until index n
A = ~new_array_log,
for (I in 2 .. N) { A[I] := true },
% We cross out the non primes
for (I in 2 .. ~floor(sqrt(N))) { % Loop goes until square root of N
if (A[I] == true) { % If a[i] is prime we cross out its multiples
for (J in I*I .. I .. N) { A[J] := false }
}
},
% We take the primes from the sieve and put them into a list
Res = ResTail,
for (K in 2 .. N) {
if (A[K] == true) { accum(!ResTail,K) }
},
ResTail = [].
accum(!R, X) :- R = [X|Tail], R := Tail.?- primes(10, Ps).Expected answer:
Ps = [2,3,5,7] ?
?- primes(100, Ps).Expected answer:
Ps = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] ?
?- primes(10000, _L), length(_L,MPrimes).Expected answer:
MPrimes = 1229 ?It reads like a program in an imperative language — for loops, if, array elements that are assigned — and it is still a Prolog module: the packages translate those constructs into ordinary Prolog when the file is compiled.
:- module(_,_).
% Example of Structure Inspection: Subterm
subterm(Term,Term). % a) A term is always a subterm of itself
subterm(Sub,Term):- % b) The arguments are also subterms:
nonvar(Term), % - Check Term not a free variable
functor(Term,_F,N),% - N is the number of arguments of Term
n_to_one(N, J), % - J is a natural between N and 1
arg(J,Term,Arg), % - Arg is the J-th argument of Term
subterm(Sub,Arg). % - Sub are the subterms of Arg
n_to_one(N, N) :- N > 0.
n_to_one(N, X) :- N > 1, N1 is N-1, n_to_one(N1, X).The base case is by definition: anything is a subterm of itself, and "is" here means unifies with. The recursive case walks into the structure: take the arity with functor/3, use n_to_one/2 to generate an argument position J — from N down to 1, on backtracking — pick that argument out with arg/3, and recurse. nonvar/1 stops it from trying to take a free variable apart.?- n_to_one( 4, N ).Expected answer:
N = 4 ? ; N = 3 ? ; N = 2 ? ; N = 1 ? ; no
?- subterm( f(a) , g(b,f(a)) ).Expected answer:
yes
?- subterm( f(b) , g(b,f(a)) ).Expected answer:
noAnd now the part worth pausing on. Because functor/3 and arg/3 both work backwards well enough, the same program enumerates the subterms:
?- subterm( X , g(b,f(a)) ).Expected answer:
X = g(b,f(a)) ? ; X = f(a) ? ; X = a ? ; X = b ? ; noFour subterms, in that order — the whole term, then down into the second argument (n_to_one/2 counts down, so the last argument comes first), then the first. It is worth thinking about how many lines this would take in another language, and whether that version would also generate.
And since "is a subterm" means unifies with a subterm, the first argument can also be a pattern:
?- subterm( f(X) , g(b,f(a)) ).Expected answer:
X = a ? ; no(What happens when the second argument contains variables is another story, to which we will come back when comparing non-ground terms.)
?- date(9,february,1947) =.. L.Expected answer:
L = [date,9,february,1947] ?
The interesting direction is backwards — from a list of pieces, build a term:
?- T =.. [date,9,february,1947].Expected answer:
T = date(9,february,1947) ?
?- _F = '+', X =.. [_F,a,b].Expected answer:
X = a+b ?Look at what just happened: _F is a variable, and it ended up as the functor of the term. One step further, and the term gets evaluated:
?- F = '+', X =.. [F,3,5], Z is X.Expected answer:
F = +, X = 3+5, Z = 8 ?
Use it only when strictly necessary. It is expensive in both time and memory.
:- module(_,_).
% Extending derivative:
deriv(sin(X), X, cos(X)).
deriv(cos(X), X, -sin(X)).
% Chain rule:
deriv(FG_X, X, DF_G * DG_X):-
FG_X =.. [_, G_X],
deriv(FG_X, G_X, DF_G),
deriv(G_X, X, DG_X).The chain rule says the derivative of f(g(x)) with respect to x is the derivative of f(g) with respect to g, times the derivative of g with respect to x. The univ call is what extracts the inner function G_X out of the composite term — the functor is discarded with _, because the rule does not care which outer function it is.?- deriv(sin(cos(x)),x,D).Expected answer:
D = cos(cos(x))* -sin(x) ?The outer derivative cos(cos(x)), times the inner one -sin(x).
?- name(hello,S).Expected answer:
S = [104,101,108,108,111] ?
?- name(A,[104,101,108,108,111]).Expected answer:
A = hello ?
?- name(A,"hello").Expected answer:
A = hello ?(With set_prolog_flag(write_strings,on) the first answer is printed as S = "hello".)
Backwards, name/2 creates atoms out of nothing — and combined with univ that means creating new functors, and therefore new structures, at run time:
?- name(N, "foo"), T =.. [N,b,c].Expected answer:
N = foo, T = foo(b,c) ?That is meta-programming: building new symbols, identifiers and functors while the program runs.
?- X='1', atom(X), name(X,S), name(Y,S), number(Y).Expected answer:
S = [49], X = '1', Y = 1 ?We started with an atom and ended with a number, and the query succeeded — which is exactly the problem. The ISO standard fixes it by splitting name/2 into two unambiguous predicates:
?- atom_codes('1', L).Expected answer:L = [49] ?
?- number_codes(1, L).Expected answer:
L = [49] ?
?- atom_codes(X, "1").Expected answer:
X = '1' ?
?- number_codes(X, "1").Expected answer:
X = 1 ?We choose which one we want; there is nothing left to guess. And each of them rejects the other kind of constant: ?- atom_codes(1, L). and ?- number_codes('1', L). both raise an error.
?- var(X), X = f(a).Expected answer:
X = f(a) ?
?- X = f(a), var(X).Expected answer:
noSame two goals, opposite order, different answers — the impurity test that we used for integer/1, applied again. nonvar/1 behaves as the exact mirror image:
?- X = f(Y), nonvar(X).Expected answer:
X = f(Y) ?
?- X = f(Y), compound(X).Expected answer:
X = f(Y) ?
?- X = f(Y), ground(X).Expected answer:
nof(Y) is compound but not ground, because Y is still free. A ground (or closed) term is one with no variables inside it at all.
What are they for? Two things: to control goal order for efficiency, and to restore some flexibility to programs that use non-reversible built-ins. The three-mode plus/3 that we wrote with the type tests could have been written with nonvar/1 instead of number/1 — though number/1 is better there, because it also checks that what arrived is actually a number.
A) The simple definition. This is the obvious definition of list length (not tail recursive):
:- module(_,_).
len([],0).
len([_|T],N) :-
len(T,TN),
N is TN+1.?- len([a,b,c],N).Expected answer:
N = 3 ?
?- len(L,3).Expected answer:
L = [_,_,_] ?A list of three holes — just as functor/3 gave us an array of holes.
There is a catch, though: take that first answer to len(L,3) and stop. If we ask for another one, len/2 keeps building longer and longer lists, none of which has length 3, and never comes back. To terminate after the first solution it would need Peano or constraint arithmetic.
B) Choosing the implementation by mode. What we can do is pick a different implementation depending on the direction. That is what the meta-logical predicates make possible. First we detect the mode and choose:
mylength(Xs,N):-
var(Xs),
integer(N),
create_list(N,Xs).
mylength(Xs,N):-
nonvar(Xs),
compute_length(Xs,N).If the list is unbound and the length is given, we create a list of length N:create_list(0,[]).
create_list(N,[_|Xs]):-
N > 0,
N1 is N - 1,
create_list(N1,Xs).Otherwise we compute the length of the list (in the same way as len/2, for now):compute_length([],0).
compute_length([_|T],N):-
compute_length(T,TN),
N is TN+1.?- mylength([a,b,c],N).Expected answer:
N = 3 ?
?- mylength(L,3).Expected answer:
L = [_,_,_] ? ; noThe first clause fires when Xs is unbound and N is an integer: there is no list to walk, so it loops on the number instead, laying down one cons cell per iteration until it hits zero. And now asking for a second answer simply gives no.
Why bother? Because create_list/2 is tail recursive — the recursive call is last, so the local variables are dead by the time it is made, the stack frame can be discarded, and the whole thing runs as a loop in constant memory. len/2 is not: its is/2 sits after the recursive call, so every pending call has to keep its stack frame until the recursion comes back.
C) Making both directions tail recursive. The other direction can get the same treatment, with an accumulating parameter. The mode detection and create_list/2 are as before:
:- module(_,_).
mylength(Xs,N):-
var(Xs),
integer(N),
create_list(N,Xs).
mylength(Xs,N):-
nonvar(Xs),
compute_length(Xs,N).create_list(0,[]).
create_list(N,[_|Xs]):-
N > 0,
N1 is N - 1,
create_list(N1,Xs).and the length is now computed with an accumulator:compute_length(L,N) :-
compute_length_(L,0,N).
compute_length_([],N,N).
compute_length_([_|T],A,N) :-
NA is A+1,
compute_length_(T,NA,N).compute_length_/3 carries a counter that starts at 0 and grows by one per cons cell; the third argument is passed untouched all the way down and receives the answer at the base case. The addition now happens before the recursive call, so this version is tail recursive too.?- mylength([a,b,c],N).Expected answer:
N = 3 ?
?- mylength(L,3).Expected answer:
L = [_,_,_] ?
Specification, executable specification, and efficient program — all in one notation. That is something Prolog is genuinely good at.
Identity tests just look:
?- f(X) == f(X).Expected answer:
yes
?- f(X) == f(Y).Expected answer:
no
Are X and X the same variable? Yes. Are X and Y? No. Now unify them and ask again:
?- X = Y, X == Y.Expected answer:
Y = X ?Yes — so ==/2 knows whether two variables have been aliased. In terms of the view of logical variables as pointers: ==/2 tells us whether two pointers point at the same place. Which means that aliasing can be inspected at run time, and that we can write something very close to imperative data structure code.
Term ordering gives a total order over all terms — which is algorithmically very convenient, because unless two terms are identical, one of them is definitely the larger:
?- f(a) @> f(b).Expected answer:
no
?- f(b) @> f(a).Expected answer:
yesThe comparison is recursive and works to any depth, on a structure of any size, without our having to navigate it.
?- f(a,b) @> g(a).Expected answer:
yesyes, even though g comes after f alphabetically — because f(a,b) has arity 2 and g(a) has arity 1, and arity is compared first. With equal arities the name decides, and f(a,b) @> g(a,b) is no as expected.
The reason is the implementation. Variables live in the heap, and comparing them compares their heap addresses — which is precisely the information a system wants, since a younger variable will be deallocated sooner on backtracking.
The standard calls this implementation dependent, and it is; but most systems, Ciao among them, behave this way. We can see that it is not the name that counts:
?- f(X) @> f(Y).Expected answer:
no
?- f(Y) @> f(X).Expected answer:
noBoth are no: in each query the variable that is written (and so created) first is the smaller one, whatever it is called.
:- module(_,_).
% Example application of comparing non-ground terms
% (use of ==/2, \==/2, @>/2, ...)
subterm_ng(Sub,Term) :- % a) A term is a subterm of another
Sub == Term. % if they are identical.
subterm_ng(Sub,Term) :- % b) The arguments are also subterms:
nonvar(Term), % Check Term not a free variable
functor(Term,_F,N), % N is number of arguments of Term
n_to_one(N, J), % J is a natural between N and 1
arg(J,Term,Arg), % Arg is the J-th argument of Term
subterm_ng(Sub,Arg).% Sub are the subterms of Arg
n_to_one(N, N) :- N > 0.
n_to_one(N, X) :- N > 1, N1 is N-1, n_to_one(N1, X).For comparison, this is the version that we had, using =/2 (implicitly, in the head of the first clause) instead of ==/2:% Version using =/2:
subterm(Term,Term). % a) A term is always a subterm of itself
subterm(Sub,Term):- % b) The arguments are also subterms:
nonvar(Term), % Check Term not a free variable
functor(Term,_F,N),% N is the number of arguments of Term
n_to_one(N, J), % J is a natural between N and 1
arg(J,Term,Arg), % Arg is the J-th argument of Term
subterm(Sub,Arg).% Sub are the subterms of ArgLet us ask both whether f(a) is a subterm of g(b,f(X)):?- subterm( f(a), g(b,f(X)) ).Expected answer:
X = a ? ; X = f(a) ? ; noIt says yes, twice, instantiating X to make it so in two different ways. And:
?- subterm_ng( f(a), g(b,f(X)) ).Expected answer:
noWhich answer is right depends entirely on what we are doing. Logically the first one is impeccable: f(a) can be a subterm of g(b,f(X)), and this is what we want if the program is to run backwards. But for meta-programming, where we care about the variables themselves, we want a no: f(a) does not literally occur there.
The difference is at its most striking when the variable occurs on both sides:
?- subterm_ng( X, g(X,f(a)) ).Expected answer:
yes
?- subterm( X, g(X,f(a)) ).Expected answer:
X = g(X,f(a)) ? ; X = f(a) ? ; X = a ? ; yessubterm_ng/2 simply observes that X occurs in the term. subterm/2 first unifies X with the whole term that contains it — there is no occurs check, so X becomes an infinite (cyclic) term — then binds it to f(a) and to a, and only as its last answer finds X itself, with no bindings.
This table summarizes how the two behave (it is a good exercise to try all of these, asking also for other solutions):
| Sub | Term | subterm_ng(Sub,Term) | subterm(Sub,Term) |
|---|---|---|---|
| f(a) | g(b,f(a)) | yes | yes |
| f(b) | g(b,f(a)) | no | no |
| g(b,f(a)) | g(b,f(a)) | yes | yes |
| X | g(b,f(a)) | no | four answers: g(b,f(a)), f(a), a, b |
| f(X) | g(b,f(a)) | no | X = a |
| f(a) | g(b,f(X)) | no | X = a, and X = f(a) |
| f(X) | g(b,f(X)) | yes | yes |
| X | g(X,f(a)) | yes | X = g(X,f(a)), X = f(a), X = a, and yes |
On ground terms the two behave identically. They depart in the cases in which a variable would have been instantiated.
:- module(_,_). % Example application of comparing non-ground terms % (use of ==/2, \==/2, @>/2, ...) % Inserting an item into an ordered list. insert_unif([], Item, [Item]). insert_unif([H|T], Item, [H|T]) :- H = Item. insert_unif([H|T], Item, [Item, H|T]) :- H @> Item. insert_unif([H|T], Item, [H|NewT]) :- H @< Item, insert_unif(T, Item, NewT).
?- insert_unif([], a, L).Expected answer:
L = [a] ?
?- insert_unif([a,b,e], c, L).Expected answer:
L = [a,b,c,e] ?Because @> and @< order any terms, this works on symbols and arbitrary data structures, not just on numbers.
And this is a version that uses ==/2 for that check:
insert_ee([], Item, [Item]). insert_ee([H|T], Item, [H|T]) :- H == Item. insert_ee([H|T], Item, [Item, H|T]) :- H @> Item. insert_ee([H|T], Item, [H|NewT]) :- H @< Item, insert_ee(T, Item, NewT).
?- insert_ee([], a, L).Expected answer:
L = [a] ?
?- insert_ee([a,b,e], c, L).Expected answer:
L = [a,b,c,e] ?So far there is no difference. It shows up when the item is an unbound variable:
?- insert_ee([a,b,e], X, L).Expected answer:
L = [X,a,b,e] ? ; no
?- insert_unif([a,b,e], X, L).Expected answer:
L = [a,b,e], X = a ? ; L = [X,a,b,e] ? ; noinsert_ee/3 places the unbound X at the front — correctly, since variables precede atoms in the standard order — and that is its only answer. insert_unif/3 instead first unifies X with a and declares the item already present; the right answer only comes second. It is the == versus = distinction, doing visible damage.
Stream control — where are we reading from and writing to:
| predicate | what it does |
|---|---|
| see(File) | File becomes the current input stream |
| seeing(File) | the current input stream is File |
| seen | close the current input stream |
| tell(File) | File becomes the current output stream |
| telling(File) | the current output stream is File |
| told | close the current output stream |
Term I/O — and this is the powerful group:
| predicate | what it does |
|---|---|
| write(X) | write the term X on the current output stream |
| nl | start a new line on the current output stream |
| read(X) | read a term (finished by a full stop) from the current input stream and unify it with X |
Character I/O, for binary work:
| predicate | what it does |
|---|---|
| put_code(N) | write the character with code N |
| get_code(N) | read the next character code and unify it with N |
?- read(X), length(X,N), write(N). typed at the prompt, answered with [1,2,3,4,5]., writes 5. Five, not the number of characters — because what came back was the list.
And write/1 is the exact converse. Hand it a pointer into the middle of an arbitrarily complicated structure and it prints whatever is there, to any depth, with no navigation code on our part.
Stream-based versions of all of these also exist, and are closer to what other languages do: open(File,Mode,S) with Mode one of read, write or append, and close(S); then write(S,X), nl(S), read(S,X), put_code(S,N), get_code(S,N). These are the ones to use when several files have to be open at once — each gets its own stream identifier.
Operators. write/1 uses whatever operator declarations are in force, so a+b is written a+b — which only reads back if the same declarations are in force at reading time. write_canonical/1 writes without operators:
?- tell(bar), write(a+b), write('.'), told. % bar contains: a+b.
?- tell(baz), write_canonical(a+b), write('.'), told. % baz contains: +(a,b).The canonical form is the safe one: it can always be read back, whatever operators happen to be declared.?- tell(foo), write( f(g(a,[1,2,3])) ), told.Expected answer:
yesTo see the exact contents of a file we use this auxiliary predicate, written with a library predicate that reads a whole file into a string:
:- use_module(library(stream_utils)).
show_file(F) :-
file_to_string(F,L),
format("~s",[L]).?- show_file(foo).Expected answer:
f(g(a,[1,2,3])) yesAnd this is an example predicate, write_list_to_file/2, which writes the elements of a list into a file, one per line, as terms that can be read back:
write_list_to_file(L,F) :-
telling(OldOutput), % Grab current output stream.
tell(F), write_list(L), told, % Write into F, close.
tell(OldOutput). % Reset previous output stream.
write_list([]).
write_list([X|Xs]):-
write(X),
% write_canonical(X),
write('.'),
nl,
write_list(Xs).?- write_list_to_file([ f(a), m, g(k)],foo), show_file(foo).Expected answer:
f(a). m. g(k). yesThe telling/1 … tell(OldOutput) sandwich is the point of the example: the predicate may be called from a program that was already writing somewhere, and it puts the output stream back where it found it.
Now we read the file back, one term at a time:
?- see(foo), read(X), read(Y), read(Z), read(W), seen.Expected answer:
W = end_of_file, X = f(a), Y = m, Z = g(k) ?The fourth read returns the atom end_of_file. Reading past that raises a past-end-of-stream error, as in any other language.
All of these input/output predicates are side effects. They are not logical, their order matters absolutely, and backtracking does not undo them. Everything that we said in the pure part about reading a program as a set of logical statements stops applying the moment one of these appears.
When executed, a cut prunes exactly two things:
Here is a small program for watching a cut at work (noop/0 just succeeds; it is there so that the debugger has a step to show for each clause):
:- module(_,_). :- discontiguous([s/1, l/1, r/1, t/1]). main(A,X,Y) :- s(A), p(X,Y). s(1) :- noop. l(a) :- noop. s(2) :- noop. l(b) :- noop. r(8) :- noop. t(10) :- noop. r(9) :- noop. t(11) :- noop. m(e) :- noop. noop. p(X,_Y) :- l(X). p(X, Y) :- r(X), !, t(Y). p(X,_Y) :- m(X).If the execution reaches the cut in the second clause of p/2, then the second alternative of r/1 is not considered, and neither is the third clause of p/2. Let us ask for all the solutions:
?- main(A,X,Y).Expected answer:
A = 1, X = a ? ; A = 1, X = b ? ; A = 1, X = 8, Y = 10 ? ; A = 1, X = 8, Y = 11 ? ; A = 2, X = a ? ; A = 2, X = b ? ; A = 2, X = 8, Y = 10 ? ; A = 2, X = 8, Y = 11 ? ; noIt is worth tracing by hand, and then following in the debugger. s(A) succeeds with A = 1. In p/2, the first clause gives X = a and then X = b through l(X). When that is exhausted, the second clause calls r(X), which succeeds with X = 8, and then the cut is executed. At that moment:
The debugger shows this very clearly. The box below is a small playground with a copy of the program (written with one clause per line, so that each step is marked on a line of its own). Press its debug button (🐞), type main(A,X,Y). at the prompt on the right, and step with Creep (or Enter). When an answer appears, type ; and Enter to ask for the next one:
:- module(cut,_).
%! \begin{miniplayground}
main(A,X,Y) :- s(A), p(X,Y).
p(X,_Y) :- l(X).
p(X, Y) :- r(X), !, t(Y).
p(X,_Y) :- m(X).
s(1) :- noop.
s(2) :- noop.
l(a) :- noop.
l(b) :- noop.
r(8) :- noop.
r(9) :- noop.
t(10) :- noop.
t(11) :- noop.
m(e) :- noop.
noop.
%! \end{miniplayground}The moment to watch comes after the fourth answer (A = 1, X = 8, Y = 11). When we ask for another one, the debugger goes from Redo: main(1,8,11) straight to Redo: s(1): nothing is tried again inside p/2, neither r(9) nor its third clause, because the cut removed them.s(1). p(X,Y):- l(X), ... r(8). s(2). p(X,Y):- r(X), !, ... r(9). p(X,Y):- m(X), ...
?- p(e,Y).Expected answer:
yesAgain: it is not the presence of the cut, it is the execution of it. Note also that the alternative that the cut removes depends on the call. Here r(8) does not match, so it is r(9) that takes us to the cut:
?- p(9,Y).Expected answer:
Y = 10 ? ; Y = 11 ? ; noThe operational one-liner. Once the cut in a clause has been executed, failing afterward takes us straight out to the parent — to whoever called this predicate. Goals to the right of the cut may still backtrack among themselves; but when failure reaches back past the cut, it leaves.
:- module(_,_).
% Types of cuts - White and Green Cuts
% ------------------------------------
% Example:
white_max(X,Y,X) :-
X > Y,
!.
white_max(X,Y,Y) :-
X =< Y.?- white_max(5,2,M).Expected answer:
M = 5 ?
?- white_max(2,5,M).Expected answer:
M = 5 ?
?- white_max(5,2,2).Expected answer:
noRemove the cut and nothing changes: the two conditions are mutually exclusive, so once X > Y has succeeded, the second clause is going to fail anyway. The cut merely says so in advance.
White cuts affect neither completeness nor correctness. Use them freely. In many cases the system introduces them automatically; writing them ourselves also documents that the clauses are exclusive.
address(X,Addr) :-
home_address(X,Addr),
!.
address(X,Addr) :-
business_address(X,Addr).
home_address(john,pfluggerville).
business_address(john,austin).
business_address(mary,boston).?- address(john,Addr).Expected answer:
Addr = pfluggerville ? ; no
?- address(mary,Addr).Expected answer:
Addr = boston ? ; noaddress/2 gives one address, preferring the home one — the clause order becomes a priority order. Without the cut we would get both addresses of john.
Another example, and a classic:
member_normal(X,[X|_]).
member_normal(X,[_|T]) :-
member_normal(X,T).
member_check(X,[X|_]) :- !.
member_check(X,[_|T]) :-
member_check(X,T).member_normal/2 gives every occurrence:?- member_normal(X,[1,2,3,4]).Expected answer:
X = 1 ? ; X = 2 ? ; X = 3 ? ; X = 4 ? ; nowhile member_check/2 stops at the first one:
?- member_check(X,[1,2,3,4]).Expected answer:
X = 1 ? ; noThis is what we want when we only need to know whether something is in the list:
?- member_normal(1,[1,2,1,4]), write('found a solution'), nl, fail.Expected answer:found a solution found a solution no
?- member_check(1,[1,2,1,4]), write('found a solution'), nl, fail.Expected answer:found a solution nofail/0 is a goal that always fails — and note that it is not impure; a = b would do the same job. Driving the search with write, nl, fail is the standard way to print every solution.
The first version finds 1 twice, because it occurs twice in the list. The cut in the base case of member_check/2 kills the alternative that the base case would otherwise have left behind, so the second occurrence is never reached.
Green cuts affect completeness but not correctness: every solution that we get is right, we just do not get all of them — which is what we asked for. They can be used when not all the solutions are needed, and they are necessary in some situations, but be careful!
Here is the first red cut that everyone writes:
:- module(_,_).
% Types of cuts - Red Cuts
% ------------------------------------
red_max(X,Y,X) :-
X > Y,
!. % Red cut!
red_max(_X,Y,Y). % :-
% X =< Y. % Missing!The reasoning feels airtight, and it is the reasoning that we would use in C: if X > Y we are done and we cut; otherwise we fell through, so X =< Y must hold, so why test it again??- red_max(5,2,M).Expected answer:
M = 5 ?
?- red_max(2,5,M).Expected answer:
M = 5 ?
?- red_max(5,2,2).Expected answer:
yesThe maximum of 5 and 2 is 2. That is a wrong answer — not wrong of the system, which did exactly what was written, but wrong of the program.
Why does it happen? red_max(5,2,2) fails against the first head, because X cannot be both 5 and 2, so the cut is never executed. It then reaches the second clause, red_max(_X,Y,Y), which says nothing about the first argument and only requires the last two to be equal — and they are.
In pure logic programming we never have to think about this, because every clause means what it says independently. With cut we do.
Compare with the version with the white cut, in which the second clause states its condition:
white_max(X,Y,X) :-
X > Y,
!.
white_max(X,Y,Y) :-
X =< Y.?- white_max(5,2,2).Expected answer:
noAnother example. The temptation here is the "rule with an exception": a year has 365 days, except leap years, which have 366.
days_in_year( X,366):-
leap_year(X),
!.
days_in_year(_X,365).
leap_year(X):-
number(X),
0 is X mod 4.Some good answers:?- days_in_year(4,D).Expected answer:
D = 366 ?
?- days_in_year(3,D).Expected answer:
D = 365 ?
?- days_in_year(3,366).Expected answer:
no
?- days_in_year(4,366).Expected answer:
yesBut wrong answers to:
?- days_in_year(4,365).Expected answer:
yes
?- days_in_year(Y,366).Expected answer:
noYear 4 apparently has both 366 days and 365, and there is no year with 366 days. We will come back to this example below.
:- module(_,_).
% Types of cuts - Red Cuts
% Useful tips regarding red cuts
% ------------------------------
red_max_delay_output(X,Y,M) :-
X > Y,
!,
M = X.
red_max_delay_output(_X,Y,Y).
% X =< Y.?- red_max_delay_output(5,2,M).Expected answer:
M = 5 ?
?- red_max_delay_output(2,5,M).Expected answer:
M = 5 ?
?- red_max_delay_output(5,2,2).Expected answer:
noCorrect now. The rule of thumb: a repeated variable (or a constant) in the head of a clause that contains a cut means that we are unifying before the cut, and that is where the surprises come from.
Tip two: use if-then-else, which is syntactic sugar over exactly this pattern, and is often the better solution:
if_then_else_max(X,Y,M) :- ( X>Y -> M=X ; M=Y).(if X>Y then M=X, else M=Y.)
?- if_then_else_max(5,2,M).Expected answer:
M = 5 ?
?- if_then_else_max(2,5,M).Expected answer:
M = 5 ?
?- if_then_else_max(5,2,2).Expected answer:
no
case(a,Y) :- !, Y = 1. case(b,Y) :- !, Y = 2. case(c,Y) :- !, Y = 3.But we would normally write it as a table:
case(a,1). case(b,2). case(c,3).which runs forwards and backwards. The cut version is only for when we actually want the case semantics.
:- module(_,_).
% Types of cuts - Red Cuts
% ------------------------
days_in_year(Y,366) :-
leap_year(Y),
!.
days_in_year(_Y,365).
leap_year(Y) :-
number(Y),
0 is Y mod 4.?- days_in_year(4,D).Expected answer:
D = 366 ?
?- days_in_year(3,D).Expected answer:
D = 365 ?So far so good. Now:
?- days_in_year(4,365).Expected answer:
yes
?- days_in_year(Y,366).Expected answer:
no
?- days_in_year(a,D).Expected answer:
D = 365 ?Year 4 has both 366 days and 365, no year has 366 days, and the atom a is a year with 365 days.
Let us read the two clauses as logic, which is the whole point of the notation. The first says: a leap year has 366 days — true, no problem. The second says: any year has 365 days. Not "any other year" — any. So leap years satisfy both, and so does a. The program says exactly that, and the system is merely agreeing with us.
days_in_year_good(Y,D) :-
leap_year(Y),
!,
D = 366.
days_in_year_good(Y,D) :-
standard_year(Y),
D = 365.
standard_year(Y) :-
number(Y),
R is Y mod 4,
R \= 0.?- days_in_year_good(4,D).Expected answer:
D = 366 ?
?- days_in_year_good(3,D).Expected answer:
D = 365 ?
?- days_in_year_good(4,365).Expected answer:
no
?- days_in_year_good(a,D).Expected answer:
noBoth clauses are now true statements standing on their own, and the cut has become white: remove it and the answers do not change. (?- days_in_year_good(Y,366). still answers no, because number/1 cannot generate years; but that is the built-in arithmetic, not the cut.)
days_in_year_delay_output(Y,D) :-
leap_year(Y),
!,
D = 366.
days_in_year_delay_output(_Y,365).?- days_in_year_delay_output(4,D).Expected answer:
D = 366 ?
?- days_in_year_delay_output(4,365).Expected answer:
no
?- days_in_year_delay_output(4,366).Expected answer:
yesThis fixes days_in_year_delay_output(4,365), which now correctly fails. But:
?- days_in_year_delay_output(Y,366).Expected answer:
nostill gives a wrong answer, since leap years exist. leap_year/1 starts with number/1, which cannot generate, so the first clause fails without reaching the cut, and the second cannot match
days_in_year_moded(Y,_D) :-
var(Y),
!,
write('{ ERROR: the year must be bound. }\n'),
abort.
days_in_year_moded(Y,D) :-
leap_year(Y),
!,
D = 366.
days_in_year_moded(_Y,365).?- days_in_year_moded(4,D).Expected answer:
D = 366 ?
?- days_in_year_moded(4,365).Expected answer:
noAnd with an unbound year:
?- days_in_year_moded(Y,366).
{ ERROR: the year must be bound. }
{ Execution aborted }Now an unbound year is refused loudly instead of answered wrongly. (This query is not a runnable box because abort/0 does what it says: it would also leave the top level of this page waiting, until the Abort button of the next query is pressed.):- use_package([assertions,modes,rtchecks]).and then we use an assertion to state the expected mode:
:- pred days_in_year_moded_assrt(+int,-int).
% Or equivalently, without using modes:
% :- pred days_in_year_moded_assrt(Y,D) : (int(Y),var(D)).
days_in_year_moded_assrt(Y,D) :-
leap_year(Y),
!,
D=366.
days_in_year_moded_assrt(_Y,365).?- days_in_year_moded_assrt(4,D).Expected answer:
D = 366 ?
?- days_in_year_moded_assrt(Y,366).Expected answer (the essential part of the run-time check error):
Requires in *calls*:
nonvar(_1)
But instead:
var(_1)?- days_in_year_moded_assrt(a,D).Expected answer (the essential part of the run-time check error):
Requires in *calls*:
int(_1)
But instead:
_1=aCalled with an unbound year, or with something that is not an integer, the run-time check reports what the predicate requires in its calls and what it found instead. It is the same protection, obtained by stating the intended mode rather than by programming around it — and the same assertion can also be checked statically, at compile time.:- module(_,_). split([],[],[]). split([X|L],[X|L1],L2) :- X >= 0, !, split(L,L1,L2). split([X|L],L1,[X|L2]) :- split(L,L1,L2). % should test X < 0
?- split([1,-1,3], L1, L2).Expected answer:
L1 = [1,3], L2 = [-1] ?Read the clauses as logic. The base case is fine either way around: the positives and the negatives of an empty list are both empty. The second clause says if X >= 0, it goes in the first list. The third says in all cases X goes in the second list — so strictly it needs its own X < 0 test.
With that test present the cut is white: it prunes a branch that would have failed anyway, and the answers are unchanged. Without the test, as above, we are relying on the cut for correctness — which works while the predicate is called forwards with a bound list, and stops working the moment it is used in any other way.
Where the cut does and does not reach. This one is subtle, and it is worth predicting the answers before running it:
:- module(_,_). k_1sol(j,k). k_1sol(X,Y) :- k(X), !, z(Y). k_1sol(l,m). k(a). k(b). z(1). z(2).What are all the solutions of k_1sol(X,Y)?
?- k_1sol(X,Y).Expected answer:
X = j, Y = k ? ; X = a, Y = 1 ? ; X = a, Y = 2 ? ; noLet us follow it. The first clause gives j,k with no cut involved. When we ask for more, the second clause runs: k(X) succeeds with X = a, and the cut executes — so k(b) disappears, and so does the third clause k_1sol(l,m). Then z(Y) runs and gives Y = 1.
When we ask for more again, z/1 still has an alternative — and the cut did not remove it, because z(Y) is to the right of the cut. So Y = 2 comes back. But there is no b,1 or b,2, because the cut did remove k(b).
One value of k, all values of z. That is a lot of control for one character.
That one predicate is what makes meta-programming possible: interpreters, shells, negation (as we will see), and implementing higher order.
:- module(_,_). % Meta-calls (call/1) and implementing apply % ------------------------------------------ r(X) :- call(X). q(a,1). q(b,2).
?- G = q(a,Y), r(G).Expected answer:
G = q(a,1), Y = 1 ?r/1 received a term and executed it as a goal. And the goal can be anything, a library predicate for example, with all its solutions:
?- G = member(Y,[1,2,3]), r(G).Expected answer:
G = member(1,[1,2,3]), Y = 1 ? ; G = member(2,[1,2,3]), Y = 2 ? ; G = member(3,[1,2,3]), Y = 3 ? ; no
Here is what we would like to write. Suppose that we are given a value, X = a, and also a predicate symbol, Y = p, and that we want to call Y(X) — to check whether a has property p, where the property arrives as data.
That cannot be written in standard Prolog. Y(X) is higher-order syntax and will not even parse. (Ciao, with the hiord package, does accept it, as we will see below — but that is an extension.)
Standard Prolog can still do it, using univ. Remember that univ spills a term into a list with the functor at the front — and that a list can contain variables. So we build the term, and then we can call it:
?- Y = p, P =.. [Y,a].Expected answer:
P = p(a), Y = p ?P is now p(a), which has the right shape to be called. That is application of a predicate passed as data — we have just invented apply.
Now let us generalize. Suppose that the symbol is member and the arguments are X and [1,2,3]. Writing them out works:
?- F = member, Args = [X,[1,2,3]], P =.. [F|Args].Expected answer:
Args = [X,[1,2,3]], F = member, P = member(X,[1,2,3]) ?But notice how easy the near-miss is. If we put the argument list in as a single element, rather than splicing it, we get a predicate of arity one:
?- F = member, L = [X,[1,2,3]], P =.. [F,L].Expected answer:
F = member, L = [X,[1,2,3]], P = member([X,[1,2,3]]) ?member/1, with a two-element list as its only argument. Not what we wanted, and almost a typo.
?- F = append, Args = [X,Y,Z], P =.. [F|Args], call(P).Expected answer:
Args = [[],Y,Y], F = append, P = append([],Y,Y), X = [], Z = Y ?Three arguments this time, and it worked without changing anything — because Args can be of any length. Wrapping those two goals in a predicate we have apply/2: it assembles the goal out of the predicate name and the list of arguments, and then calls it:
apply(P,Args) :-
G =.. [P|Args],
call(G).?- P = q, apply(P,[a,Y]).Expected answer:
P = q, Y = 1 ?
?- P = q, apply(P,[X,Y]).Expected answer:
P = q, X = a, Y = 1 ? ; P = q, X = b, Y = 2 ? ; noThe predicate arrived in a variable.
There is another route, incidentally, called a Warren transformation, and the call/n family that we see next is a third. And once we have any of them, map, fold and the rest are ordinary library predicates.
For example, with apply/2 in hand, mapping a predicate onto a list of tuples of arguments is three lines:
maptuples(_P,[]).
maptuples(P,[Tuple|RTuples]) :-
apply(P,Tuple),
maptuples(P,RTuples).?- maptuples(q,[[a,X],[b,Y]]).Expected answer:
X = 1, Y = 2 ?
?- maptuples(append, [ [ [a],[c,d], X ], [ X, [e,f], Y ], [ X, Y, Z ] ]).Expected answer:
X = [a,c,d], Y = [a,c,d,e,f], Z = [a,c,d,a,c,d,e,f] ?In that last query the three calls to append/3 are chained through their shared variables: the result of the first one, X, is an input of the other two.
:- module(_,_). % Meta-calls: call/n % ------------------ q(a,1). q(b,2).Packages are per module, and the top level is one more module, so to use call/n in our queries we first load hiord into the top level:
?- use_package(hiord).Expected answer:
Note: module hiord_rt already in executable, just made visible yes
?- P = q, call(P,X,Y).Expected answer:
P = q, X = a, Y = 1 ?
?- P = q(a), call(P,Y).Expected answer:
P = q(a), Y = 1 ?Both spellings work: we can hand over the bare predicate name and supply both arguments, or hand over a partially applied term and supply the rest. It works for library predicates just as well:
?- P = append, call(P,[1,2],[3,4],Y).Expected answer:
P = append, Y = [1,2,3,4] ?
?- P = append(X,Y), call(P,[1,2,3,4]).Expected answer:
P = append([],[1,2,3,4]), X = [], Y = [1,2,3,4] ?— and on backtracking this last one gives all the splittings, because the predicate passed in is still the relational append/3.
plus(X,Y,Z) :- number(X),number(Y), Z is X + Y. plus(X,Y,Z) :- number(X),number(Z), Y is Z - X. plus(X,Y,Z) :- number(Y),number(Z), X is Z - Y.and load the library into the top level:
?- use_module(library(hiordlib)).Expected answer:
Note: module hiordlib already in executable, just made visible yes
?- maplist(plus, [1,2,3], [4,5,6], R).Expected answer:
R = [5,7,9] ?
?- maplist(plus, [1,2,3], L2, [5,7,9]).Expected answer:
L2 = [4,5,6] ?maplist ran backwards, because the predicate it was given runs backwards. Higher-order predicates inherit the reversibility of what is passed to them — something that a functional map cannot do, since a function only goes one way.
The same happens with append/3:
?- maplist(append, [ [a,b], [1,2] ], [ [c,d], [3,4] ], Z).Expected answer:
Z = [[a,b,c,d],[1,2,3,4]] ?
?- maplist(append, [ [a,b], [1,2] ], Y, [[a,b,c,d],[1,2,3,4]] ).Expected answer:
Y = [[c,d],[3,4]] ?And with shared variables it gets quietly spectacular:
?- maplist(append, [ [a], X, X ], [ [c,d], [e,f], Y ], [ X, Y, Z] ).Expected answer:
X = [a,c,d], Y = [a,c,d,e,f], Z = [a,c,d,a,c,d,e,f] ?Three appends whose inputs and outputs are wired to each other, as in the maptuples/2 query above.
:- module(_,_). % Some additional functionality via the hiord package % --------------------------------------------------- q(a,1). q(b,2).The package has to be loaded in the top level, which we have already done above with ?- use_package(hiord). Then the special syntax for call/n can be used:
?- P = q, P(X,Y).Expected answer:
P = q, X = a, Y = 1 ?
?- P = append, P([1,2],[3,4],Y).Expected answer:
P = append, Y = [1,2,3,4] ?
?- P = append(X,Y), P([1,2,3,4]).Expected answer:
P = append([],[1,2,3,4]), X = [], Y = [1,2,3,4] ?Anonymous predicates — read the _ as a lambda:
?- P = { _(X,Y) :- Y is X+1 }, P(3,R).Expected answer:P = {''(X,Y):-Y is X+1},
R = 4 ?And they can be passed straight to maplist:?- maplist({ _(X,Y) :- Y is X+1 }, [1,2,3], R).Expected answer:R = [2,3,4] ?There is much more in the hiordlib library.
findall(Term, Goal, ListResults): ListResults is the list of all instances of Term for which Goal succeeds. If there are none, it is []. For it to terminate, the number of solutions must of course be finite, and enumerable in finite time.
?- findall(X, member(X,[d,a,b,c,b,d]), L).Expected answer:
L = [d,a,b,c,b,d] ?The goal can be any goal, a conjunction for example:
?- findall(X, (member(X,[d,a,b,c,b,d]), X @< c), L).Expected answer:
L = [a,b,b] ?For the rest of the examples we will use this small database:
likes(bill, cider). likes(dick, beer). likes(tom, beer). likes(tom, cider). likes(harry, beer). likes(jan, cider).
?- findall(X, likes(X,Y), S).Expected answer:
S = [bill,dick,tom,tom,harry,jan] ?tom appears twice, because he satisfies the goal twice — findall/3 collects solutions, not distinct values.
The first argument is a pattern, and it does more than name a variable. It says what to build out of each solution:
?- findall(beer_lover(X), likes(X,beer), S).Expected answer:
S = [beer_lover(dick),beer_lover(tom),beer_lover(harry)] ?Whatever term we write there is instantiated once per solution and collected. That is what makes these predicates as useful as they are.
And an empty result is an empty list, not a failure:
?- findall(X, likes(X,water),S).Expected answer:
S = [] ?
?- setof(X, member(X,[d,a,b,c,b,d]), L).Expected answer:
L = [a,b,c,d] ?Three differences from findall/3 matter:
?- bagof(X, member(X,[d,a,b,c,b,d]), L).Expected answer:
L = [d,a,b,c,b,d] ?
The ordering that setof/3 uses is the standard order of terms, the same one that @< uses — which is what makes it able to sort any answers, not just numbers or atoms.
The backtracking behavior is the interesting one, and it is the part that seems strange at first.
Let us think about what we are asking for in setof(X, likes(X,Y), S). Y appears in the goal but not in the pattern, so it is a free variable — and it is genuinely unclear what we want. All the X for every Y lumped together? Or all the X for each Y separately?
So setof/3 answers once per drink:
?- setof(X, likes(X,Y), S).Expected answer:
S = [dick,harry,tom], Y = beer ? ; S = [bill,jan,tom], Y = cider ? ; noThat is a group-by, obtained for free. Wrapped in another aggregation it gives the whole grouping in one term:
?- findall( Y-L , setof(X,likes(X,Y),L), Pairs).Expected answer:
Pairs = [beer-[dick,harry,tom],cider-[bill,jan,tom]] ?
?- setof((Y,S), setof(X, likes(X,Y), S), SS).Expected answer:
SS = [(beer,[dick,harry,tom]),(cider,[bill,jan,tom])] ?If that is not what we wanted, we have to say so: Y^Goal is existential quantification, read "there exists a Y such that …". Quantifying Y away we get everybody, once each:
?- setof(X, Y^likes(X,Y), S).Expected answer:
S = [bill,dick,harry,jan,tom] ?Note that tom is not repeated, even though he appears twice in the database — setof/3 always sorts and removes duplicates.
And with no solutions at all, setof/3 fails where findall/3 returned []:
?- setof(X, likes(X,water), S).Expected answer:
nobagof/3 backtracks over the free variables in the same way, and also fails when there are no solutions, but it neither sorts nor removes duplicates:
?- bagof(X, likes(X,Y), S).Expected answer:
S = [dick,tom,harry], Y = beer ? ; S = [bill,tom,jan], Y = cider ? ; no
?- bagof(X, Y^likes(X,Y), S).Expected answer:
S = [bill,dick,tom,tom,harry,jan] ?
?- bagof(X, likes(X,water),S).Expected answer:
no
subset([],[]).
subset([X|Xs],[X|Ys]) :-
subset(Xs,Ys).
subset([_|Xs],Ys) :-
subset(Xs,Ys).
powerset(Set,Pset) :-
setof(X,subset(Set,X),Pset).?- subset([1,2,3],S).Expected answer:
S = [1,2,3] ? ; S = [1,2] ? ; S = [1,3] ? ; S = [1] ? ; S = [2,3] ? ; S = [2] ? ; S = [3] ? ; S = [] ? ; no
?- powerset([1,2,3],Pset).Expected answer:
Pset = [[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]] ?subset/2 generates the subsets one at a time on backtracking; setof/3 gathers and sorts them. Eight of them, as it should be.
:- module(_,_). % Meta-calls and cut: Negation as failure % --------------------------------------- not( Goal) :- call(Goal), !, fail. not(_Goal).Let us read the two clauses. If Goal succeeds, we execute the cut — killing the second clause — and then fail: so not(Goal) fails, and because the cut removed every alternative before it, there is nowhere left to backtrack to. If Goal fails, the first clause fails before the cut, and the second clause succeeds unconditionally. Negation, in two lines, out of call/1, ! and fail/0.
?- not( member(c, [a, k, l]) ).Expected answer:
yesIt is available from the library as the prefix operator \+/1:
?- \+ member(c, [a, k, l]).Expected answer:
yes
?- X = 1, \+ X = 2.Expected answer:
X = 1 ?
?- \+ X = 1.Expected answer:
nono — because a free X can be unified with 1, so the goal being negated succeeds.
Here is the difference, on a concrete question — does this list start with 1?
?- L = [X,2,3], append([1],R,L).Expected answer:
L = [1,2,3], R = [2,3], X = 1 ?It answered yes — and changed the list: X got bound to 1. Now with the double negation:
?- L = [X,2,3], \+ \+ append([1],R,L).Expected answer:
L = [X,2,3] ?Same answer to the question, and L is untouched. Note also that the cut inside \+/1 means that we get one yes-or-no answer and no choice points, where the direct call would have left them.
Termination. The termination of \+ Goal depends on the termination of Goal: it terminates if the search for Goal reaches a success node before an infinite branch. If Goal loops, so does its negation.
And now the danger. Another example:
unmarried_student(X) :-
\+ married(X),
student(X).
student(joe).
married(john).?- unmarried_student(joe).Expected answer:
yes
?- unmarried_student(john).Expected answer:
no
?- unmarried_student(X).Expected answer:
no
What happened: \+ married(X) is called with X still unbound. It asks "is there any X such that married(X)?" — and there is, john — so married(X) succeeds, and the negation fails. The whole conjunction dies before student(X) is ever reached.
The deeper reason is the one above: negation does not instantiate. Even conceptually there is nothing for it to return — it does not know of any X for which the negation holds, only that the negation does not hold in general.
Asked about specific people it behaves perfectly: unmarried_student(joe) is yes, and unmarried_student(john) is no — for two independent reasons, since John is married and is not a student in this database. It is only generation that breaks.
Negation as failure is only correct for ground goals, that is, goals which contain no variables, and it is the programmer's responsibility to ensure that. The built-in ground/1 checks this property:
?- ground(unmarried_student(joe)).Expected answer:
yes
?- ground(unmarried_student(X)).Expected answer:
noHere is an example in which the negated goal is ground whenever the predicate is called with two given sets:
overlap(S1,S2) :- % S1 and S2 overlap if they share an element
member(X,S1), member(X,S2).
disjoint(S1,S2) :- \+ overlap(S1,S2).?- disjoint([1,2,3,4],[a,b,c]).Expected answer:
yes
?- disjoint([1,2,3,4],[2,4,c]).Expected answer:
noFor unmarried_student/1, the most frequent fix is simply to put the generator first, so that the variable is bound by the time the negation runs:
unmarried_student(X) :- student(X), \+ married(X).Now student(X) generates joe, and only then is married(joe) negated: unmarried_student(X) answers X = joe, and nobody else. Generate, then test — the same lesson that we learned about the order of goals in pure programs, with sharper consequences.
:- module(_,_).
% Meta-calls and cut: Negation as failure -- ensuring correctness
% ---------------------------------------------------------------
unmarried_student(X) :-
\+ married(X),
student(X).
student(joe).
married(john).?- unmarried_student(X).Expected answer:
nowhich we know is wrong, since an unmarried student does exist. Instead of hoping that the negation is called with a ground goal, we can check it. This is a better, safer implementation of negation:
not_(G) :-
ground(G), !,
\+ G.
not_(G) :-
write('ERROR: Non-ground goal in negation: '), write(G), nl,
abort.
unmarried_student_with_check(X) :-
not_(married(X)),
student(X).?- unmarried_student_with_check(joe).Expected answer:
yes
?- unmarried_student_with_check(john).Expected answer:
noAnd with an unbound argument (again not as a runnable box, since it calls abort/0):
?- unmarried_student_with_check(X).
ERROR: Non-ground goal in negation: married(_1541)
{ Execution aborted }The error is reported, and the execution aborted, instead of quietly answering no.Or we can state the condition as an assertion, and let the system check it. We load the assertions package and the run-time checking of assertions:
:- use_package([assertions,modes,rtchecks]).We define not__/1, which simply calls \+, but protected by an assertion which requires the goal in G to be ground on calls (the : field of the assertion is the call condition):
:- pred not__(G) : ground(G). not__(G) :- \+ G.and we use this not__/1 in the example:
assrt_unmarried_student(X) :-
not__( married(X) ),
student(X).The assertion is then checked, in this case dynamically (by rtchecks); the same assertion can also be verified statically:?- assrt_unmarried_student(joe).Expected answer:
yes
?- assrt_unmarried_student(X).Expected answer (the essential part of the run-time check error):
Requires in *calls*:
ground(G)
But instead:
G=married(_)once(X) :- call(X), !.
?- member(X,[1,2,3]).Expected answer:
X = 1 ? ; X = 2 ? ; X = 3 ? ; no
?- once(member(X,[1,2,3])).Expected answer:
X = 1 ? ; no
Note first that fail itself needs nothing special: it can be programmed in pure logic.
:- module(_,_). % Meta-calls and cut: cut-fail % ---------------------------- myfail :- a=b.The example is ground/1 itself — a term is ground if it contains no variables, so we use the cut-fail to fail as soon as a free variable is found. Since ground/1 is a built-in, we first tell the compiler that we are redefining it:
:- redefining(ground/1).and this is the definition, using cut and fail:
ground(Term) :-
var(Term),
!,
fail.
ground(Term) :-
nonvar(Term),
functor(Term,_F,N),
ground_(N,Term).
ground_(0,_T). % All subterms traversed
ground_(N,T) :-
N>0,
arg(N,T,Arg),
ground(Arg),
N1 is N-1,
ground_(N1,T).?- ground(a).Expected answer:
yes
?- ground(X).Expected answer:
no
?- ground(f(a,f(X,d),b)).Expected answer:
no
?- ground(f(a,f(c,d),Z)).Expected answer:
noThe first clause is the cut-fail: if the term is a variable, we cut away the second clause and fail, committing to "no". The rest is the same descent through functor/3 and arg/3 as in subterm/2. It is a good one to follow in the debugger.
Useful, and dangerous for the same reason as all cuts: the failure is committed, so there is no backtracking into an alternative reading.
There are cases where assertion and retraction can be logically justified:
The behavior and the requirements differ between Prolog implementations. Typically a new predicate, one that is not already defined in the program, can always be asserted; otherwise it must be declared :- dynamic.
:- module(_,_).A) New, dynamically created predicates are directly modifiable. There is no p/1 in the program:
?- p(X).Expected answer:
{ERROR: user:p/1 - existence error: procedure:user:p/1 does not exist}We add a fact to it, which creates the predicate:?- assert(p(a)).Expected answer:
yes
?- p(X).Expected answer:
X = a ?
?- assert(p(b)).Expected answer:
yes
?- p(X).Expected answer:
X = a ? ; X = b ? ; noand now we remove the two facts again:
?- retract(p(a)).Expected answer:
yes
?- retract(p(b)).Expected answer:
yes
?- p(X).Expected answer:
noThe answer is no, and not an error: the predicate still exists, it just has no clauses. abolish/1 removes the predicate altogether — after which calling it is again an existence error, not a failure:
?- abolish(p/1).Expected answer:
yes
?- p(X).Expected answer:
{ERROR: user:p/1 - existence error: procedure:user:p/1 does not exist}B) A predicate that is already defined in the program must be declared dynamic for it to be modifiable:related(3,4).
:- dynamic related/2.We define some operations on related/2:
relate_numbers(X,Y) :- assert(related(X,Y)). unrelate_numbers(X,Y) :- retract(related(X,Y)).
?- related(3, 4).Expected answer:
yes
?- related(1, 2).Expected answer:
no
?- relate_numbers(1, 2).Expected answer:
yes
?- related(1, 2).Expected answer:
yes
?- related(X, Y).Expected answer:
X = 3, Y = 4 ? ; X = 1, Y = 2 ? ; no
?- unrelate_numbers(1, 2).Expected answer:
yes
?- related(1, 2).Expected answer:
noC) Rules can be asserted too, not just facts. Since a clause is a term, we build the term and assert it. This is a definition of append that we can add or delete dynamically:
:- dynamic app/3.
% Create the definition of append
define_app :-
assert( app([], X, X) ),
assert( ( app([X|Y], Z, [X|W]) :- app(Y,Z,W) ) ).
% Erase the definition of append
erase_app :-
abolish(app/3).Note the extra parentheses around the rule, needed because :- has priority 1200, well above the 1000 of the comma. At the beginning app/3 is declared, but has no clauses:?- app([1,2],[3,4],Y).Expected answer:
no
?- define_app.Expected answer:
yes
?- app([1,2],[3,4],Y).Expected answer:
Y = [1,2,3,4] ?
?- app(X,Y,[1,2,3,4]).Expected answer:
X = [], Y = [1,2,3,4] ? ; X = [1], Y = [2,3,4] ? ; X = [1,2], Y = [3,4] ? ; X = [1,2,3], Y = [4] ? ; X = [1,2,3,4], Y = [] ? ; noA complete append/3, written into the program at run time. And it can be erased again:
?- erase_app.Expected answer:
yes
?- app(X,Y,[1,2,3,4]).Expected answer:
{ERROR: 280_dynamic_assert:app/3 - existence error: procedure:280_dynamic_assert:app/3 does not exist}?- C = (smaller(X,Y) :- X < Y), assert(C).Expected answer:
C = (smaller(X,Y):-X<Y) ?
?- smaller(1,2).Expected answer:
yes
?- smaller(2,1).Expected answer:
no
retractall/1 removes every clause of a dynamic predicate at once, which is the usual way of starting over.
:- module(_,_).
% Dynamic program modification example: using lemmas
% --------------------------------------------------
fib(0, 0).
fib(1, 1).
fib(N, F) :-
N > 1,
N1 is N - 1,
N2 is N - 2,
fib(N1, F1),
fib(N2, F2),
F is F1 + F2. The same, in functional notation::- use_package(fsyntax). :- fun_eval arith(true). ffib(0) := 0. ffib(1) := 1. ffib(N) := ~ffib(N-1) + ~ffib(N-2) :- N>1.
?- ffib(20,Y).Expected answer:
Y = 6765 ?We can already see why this definition is bad: computing fib(N-1) and fib(N-2) separately throws away all the work that the first one did, because fib(N-1) computed fib(N-2) along the way.
If we print a line on every call and ask for position 4 we see it: the calls are for positions 3, 2, 1, 0, 1, 2, 1, 0 — position 3 is computed once, position 2 twice, position 1 three times. The number of calls is exponential: each new number recomputes the whole tree beneath it.
Now a version that records lemmas, that is, things that have already been proved. First we define a table (a dynamic predicate) which at the beginning holds the first two elements:
:- dynamic lemma_fib/2. lemma_fib(0, 0). lemma_fib(1, 1).and to compute the rest:
lfib(N, F) :-
% First check if we have the Nth element in the table,
% and we take it from there.
lemma_fib(N, F),
!.
lfib(N, F) :-
% Else, we compute the Nth number...
N > 1,
N1 is N - 1,
N2 is N - 2,
lfib(N1, F1),
lfib(N2, F2),
F is F1 + F2,
% ...and once we have it we record it:
assert(lemma_fib(N, F)). The lemma version differs from the first one in exactly two places: it looks the number up, in case we already have it, and it records what it has just computed. As soon as it reaches a position that is in the table it stops descending, so even the first call needs few steps: for position 4 the calls are 3, 2, 1, 0, 1, 2. And a second call pays even more: asking for position 5 after position 4 needs only two look-ups and one addition, because 4 and 3 are both already known.We can compare the computation times (the values may have to be adjusted for other processors):
?- fib(30,Y).Expected answer:
Y = 832040 ?
?- fib(32,Y).Expected answer:
Y = 2178309 ?
?- lfib(30,Y).Expected answer:
Y = 832040 ?
?- lfib(35,Y).Expected answer:
Y = 9227465 ?Run directly in Ciao on a laptop, fib(30,Y) takes about 0.2 seconds, fib(32,Y) about 0.9, and fib(35,Y) about 3.6 seconds: the time grows exponentially with the position. lfib(30,Y) takes about two hundredths of a millisecond. That is almost four orders of magnitude, and the gap widens with N. In fact lfib/2 goes far beyond where the first version can follow:
?- lfib(200,Y).Expected answer:
Y = 280571172992510140037611932413038677189525 ?(?- lfib(1000,Y). also answers at once, with a number of 209 digits.)
A (white) cut in each of the two facts removes those choice points, and fib(35,Y) then needs about 20 MB, and less than a second. These are the useless choice points that we talked about when classifying the cuts.
As the saying goes: those who cannot remember the past are condemned to repeat it.
And there is a practical trap. The lemmas survive: when experimenting at the top level and getting results that cannot be explained (or times that are too good), remember that the assertions of a previous run may still be there. Reload the module, or do retractall(lemma_fib(_,_)) and assert the base cases again, before timing anything.
:- module(_,_,[]). % Meta-interpreters % ----------------- :- use_package(dynamic_clauses).We declare lappend/3 dynamic, and thus visible to clause/2:
:- dynamic lappend/3. lappend([],X,X). lappend([X|Y],Z,[X|W]) :- lappend(Y,Z,W).We give clause/2 a head pattern, and it enumerates the matching clauses on backtracking. For lappend/3 it returns the two that we expect:
?- clause(lappend(A,B,C),Body).Expected answer:
A = [], Body = 'basiccontrol:true', C = B ? ; A = [_C|_A], Body = '300_meta_interpreter:lappend'(_A,B,_B), C = [_C|_B] ? ; no(The bodies come back with each goal qualified by the module in which it is defined: true is in basiccontrol, and lappend/3 in our own module.)
But it does not execute anything. The difference shows up on rules: if we assert the fact rel(0,0), then clause(rel(X,Y),B) gives X = 0, Y = 0; if we assert the rule rel(X,Y) :- X = 0, Y = 0 — the same meaning — then clause/2 gives back the body unexecuted, and X and Y stay free. For a fact, unifying and executing happen to be the same thing; for a rule they are not.
With it we can write an interpreter for Prolog, in Prolog, in three lines. This is the "vanilla" meta-interpreter:
solve( true ) :- !. solve( (A,B) ) :- !, solve(A), solve(B). solve( A ) :- clause(A,B), solve(B).Let us read the three clauses: true is solved, so we are finished; a pair (A,B) is solved by solving A and then B — and it is a pair because that is how clause bodies are built, conjunctions nested to the right with ,/2; and anything else is solved by finding a clause whose head it matches and solving the body of that clause.
?- solve(lappend([1,2],[3,4],L)).Expected answer:
L = [1,2,3,4] ?
?- solve(lappend(X,Y,[1,2,3,4])).Expected answer:
X = [], Y = [1,2,3,4] ? ; X = [1], Y = [2,3,4] ? ; X = [1,2], Y = [3,4] ? ; X = [1,2,3], Y = [4] ? ; X = [1,2,3,4], Y = [] ? ; no
solve( true ) :- !. solve( (A,B) ) :- !, solve(A), solve(B). solve( A ) :- clause(A,B), solve(B).are a skeleton, and the point is how easily it can be extended to do many tasks: tracing, debugging, explanations in expert systems, implementing other computation rules, ...
Tracing is the easiest. With a write/1 and nl/0 in the third clause, every goal that the interpreter attempts is printed — without modifying the program being interpreted at all. Placed after the recursive call instead, they show the state on the way back out, which is how the answer list gets built. That is already a usable debugger, in two extra goals.
With one more argument instead we have an interpreter that counts the number of (forward) steps. Again we declare lappend/3 dynamic, and thus visible to clause/2:
:- module(_,_,[]). % Meta-interpreters: extending the basic meta-interpreter % ------------------------------------------------------- % Ciao-specific: version of 'dynamic' package that makes dynamic % clauses visible to `clause/2` :- use_package(dynamic_clauses). :- dynamic lappend/3. lappend([],X,X). lappend([X|Y],Z,[X|W]) :- lappend(Y,Z,W).and this is the version of the meta-interpreter with the extra argument:
csolve( true, 0) :- !. csolve( (A,B), N) :- !, csolve(A,NA), csolve(B,NB), N is NA+NB. csolve( A, N) :- clause(A,B), csolve(B,N1), N is N1+1.
?- csolve(lappend([1,2],[3,4],L),N).Expected answer:
L = [1,2,3,4], N = 3 ?Three steps. Now a question: what does the cost (the number of steps) of a call to lappend/3 depend on?
?- csolve(lappend([1,2,a,b],[3,4],L),N).Expected answer:
L = [1,2,a,b,3,4], N = 5 ?
?- csolve(lappend([1,2],[3,4,a,b],L),N).Expected answer:
L = [1,2,3,4,a,b], N = 3 ?Lengthening the first list costs steps; lengthening the second costs nothing. lappend/3 recurses on its first argument only, and the cost is the length of that list plus one — measured here, not argued for.
The three steps of the first query line up exactly with the program: one for each element of [1,2], and one more where the base case lappend([],X,X) matches. This is a genuinely useful way of finding the complexity of a predicate: we get a number rather than an argument.
Let us start with why ordinary append/3 is expensive. We have a pointer X to [1,2,3], ending in [], and a pointer Y to [4,5]. append(X,Y,Z) builds the result by taking the head off the first list and putting it at the front of the result, over and over — that is, it copies the first list. Only when it reaches the base case, append([],L,L), does it make the last cell point at Y. So the second list is not copied; the first one is, entirely. That is where the cost comes from.
What we would rather do is attach something at the end of the first list. And we can — if we leave the tail as a free variable and keep a pointer to it. Then appending is a single unification: point the tail at the second list. Constant time.
[1,2,3] is a closed list: it ends in [], and we cannot add to the end without walking to it first — which is exactly why append/3 costs the length of its first argument.
An incomplete (or open) list ends in a variable: [1,2,3|T]. Now we can add at the end, by instantiating T. The idea of a difference list is to carry that variable around with the list, in a pair L-T, so that we always have a pointer to the end.
The -/2 is just a functor pairing the list with its own tail; nothing arithmetic is going on. It is traditional, and it is where the name "difference list" comes from — we are carrying the list together with what must be subtracted from it.
Having a pointer to the end of the list is what allows us to append in constant time:
append_dl(B1-E1,B2-E2,B3-E3) :- B3=B1, E3=E2, B2=E1.The result starts where the first list starts, ends where the second ends, and the second list is plugged into the hole at the end of the first. Written more compactly, all three unifications happen in the head:
append_dl(X-Y,Y-Z,X-Z).which is why append_dl/3 is a fact, and runs in constant time regardless of the lengths.
The same trick generalizes. These are really incomplete data structures, not merely incomplete lists: leaving variables at the ends of any structure allows us to extend it there. Difference (open-ended) trees have variables at the leaves, and from them we get dictionaries and queues. It is one of the great tricks of logic programming — and specifically of Prolog.
?- L = [1,2,3|T]-T, L = _-T, T = [4,5].Expected answer:
L = [1,2,3,4,5]-[4,5], T = [4,5] ?The idea can be expressed as a (pseudo-)type:
dlist(X-X). dlist([_|DL]-X) :- dlist(DL-X).The empty difference list is the pair whose two halves are the same variable: X-X, the head pointing at the tail with nothing in between. These are its first answers (there are infinitely many, so do not ask for all of them):
?- dlist(L).Expected answer:
L = _A-_A ? ; L = [_|_A]-_A ? ; L = [_,_|_A]-_A ?
?- dlist([1,2,3|T]-T).Expected answer:
T = [1,2,3|T] ?The first clause, dlist(X-X), unifies the open list with its own tail, which (there being no occurs check) creates a cyclic term, instead of recognizing a list of three elements. A real check needs var/1 and ==/2:
dlist(X-Y) :- var(X), !, X == Y. dlist([_|DL]-X) :- dlist(DL-X).Note the ! and the ==/2 — this is not pure; it is a Prolog program, and it could not have been written in pure logic programming.
Now let us create two difference lists and append them, by hand, with no append_dl/3 at all: we just unify the second list with the tail of the first one.
?- L1 = [1,2,3|X], L2 = [4,5|Y], L2=X.Expected answer:
L1 = [1,2,3,4,5|Y], L2 = [4,5|Y], X = [4,5|Y] ?L1 is now [1,2,3,4,5|Y], and one unification did it, in constant time. And this is the predicate for appending difference lists:
append_dl(B1-E1,E1-E2,B1-E2).
?- append_dl( [1,2,3|X]-X, [4,5|Y]-Y, L).Expected answer:
L = [1,2,3,4,5|Y]-Y, X = [4,5|Y] ?L has the resulting (appended) difference list.
It has other uses too, because it is a fact and everything is unification. Checking:
?- append_dl( [1,2,3|X]-X, [4,5|Y]-Y, [1,2,3,4,5|Z]-Z).Expected answer:
X = [4,5|Y], Z = Y ?and subtracting: given the result and the second list, it recovers the first one.
?- append_dl( L-X, [4,5|Y]-Y, [1,2,3,4,5|Z]-Z).Expected answer:
L = [1,2,3,4,5|Y], X = [4,5|Y], Z = Y ?But, unlike append/3, it does not enumerate the ways of splitting a list. There is only one solution:
?- append_dl( L1-X, L2-Y, [1,2,3,4,5|Z]-Z).Expected answer:
L1 = [1,2,3,4,5|Y], X = L2, Z = Y ?
:- module(_,_).
qsort([],[]).
qsort([X|L],S) :- % Take first element of list in X
partition(L,X,LS,LB), % LS are the elements of L < X
% LB are the elements of L >= X
qsort(LS,LSS), % LSS is LS sorted
qsort(LB,LBS), % LBS is LB sorted
append(LSS,[X|LBS],S). % We append the small ones sorted to
% the big ones sorted (w/X in front)
partition([],_P,[],[]).
partition([E|R],P,[E|Smalls],Bigs) :- % Take first element E
E < P, % If E < P add to list of smaller ones
partition(R,P,Smalls,Bigs).
partition([E|R],P,Smalls,[E|Bigs]) :-
E >= P, % If E >= P add to list of larger ones
partition(R,P,Smalls,Bigs).?- qsort([5,2,1,3,7,6], SL).Expected answer:
SL = [1,2,3,5,6,7] ?This is the same program again, with the values that the variables take in the top call written in the comments:
:- module(_,_).
qsort([],[]).
qsort([X|L],S) :- % X=5, L=[2,1,3,7,6]
partition(L,X,LS,LB), % LS=[2,1,3]
% LB=[7,6]
qsort(LS,LSS), % LSS=[1,2,3]
qsort(LB,LBS), % LBS=[6,7]
append(LSS,[X|LBS],S). % call: append([1,2,3],[5,6,7],S)
% S=[1,2,3,5,6,7]
partition([],_P,[],[]).
partition([E|R],P,[E|Smalls],Bigs) :-
E < P,
partition(R,P,Smalls,Bigs).
partition([E|R],P,Smalls,[E|Bigs]) :-
E >= P,
partition(R,P,Smalls,Bigs).?- qsort([5,2,1,3,7,6], SL).Expected answer:
SL = [1,2,3,5,6,7] ?In the top call X = 5 and L = [2,1,3,7,6]; partition gives LS = [2,1,3] and LB = [7,6]; sorting those gives [1,2,3] and [6,7]; and the final call is append([1,2,3],[5,6,7],S).
That append/3 is the waste. It walks the whole left half again, at every level of the recursion.
Consider the input list first. We have to walk down it anyway — there is no way to sort a set without looking at every element — and we never append to it. So it can stay an ordinary list.
Now the result. That is where the appends are, because we have the small ones and the big ones and have to join them. So that is what becomes a difference list.
And a pleasant consequence: partition/4 does not change at all. It takes a normal list and a pivot and produces two normal lists — which is exactly what the recursive calls want in their first argument.
Version 1 — with the -/2 functor and every unification written out, so that we can see what is being connected to what (again, the comments show the values in the top call):
:- module(_,_).
qsort_dl(L,SL) :- % L = [5,2,1,3,7,6]
qsort_dl_(L,SL-SLE), % SL = [1,2,3,5,6,7|SLE]
SLE = []. % SL = [1,2,3,5,6,7]
qsort_dl_([],SLE-SLE).
qsort_dl_([X|L],SL-SLE) :- % X = 5, L = [2,1,3,7,6]
partition(L,X,S,B), % S = [2,1,3], B = [7,6]
qsort_dl_(S,SS-SSE), % SS = [1,2,3|SSE]
qsort_dl_(B,BS-BSE), % BS = [6,7|BSE]
SSE = [X|BS], % SSE = [5,6,7|BSE]
SL = SS, % SL = [1,2,3,5,6,7|BSE]
SLE = BSE. % SL = [1,2,3,5,6,7|SLE]partition/4 is the same as in the standard quicksort:partition([],_P,[],[]).
partition([E|R],P,[E|Smalls],Bigs) :- % Take first element E
E < P, % If E < P add to list of smaller ones
partition(R,P,Smalls,Bigs).
partition([E|R],P,Smalls,[E|Bigs]) :-
E >= P, % If E >= P add to list of larger ones
partition(R,P,Smalls,Bigs).?- qsort_dl([5,2,1,3,7,6], SL).Expected answer:
SL = [1,2,3,5,6,7] ?Let us reason about it recursively, which means believing that the recursion works (and then running it in the debugger). We give it [5,2,1,3,7,6]; the pivot is 5, and partition/4 gives S = [2,1,3] and B = [7,6] as ordinary lists. Now we sort those: the first call returns [1,2,3] as a difference list, from SS to SSE; the second returns [6,7], from BS to BSE.
Now comes the point where the old version did the append/3 — and here is the magic. What came back are difference lists, so we have a handle on the end of each. Three unifications suffice:
No traversal, no append/3. And the top-level qsort_dl/2 then does one last thing for the benefit of a caller who knows nothing about difference lists: SLE = [] closes the open tail, converting the difference list back into an ordinary one.
The debugger lets us do exactly this: believe the recursion, and look at the three unifications. In the box below, press the debug button (🐞), type qsort_dl([5,2,1,3,7,6],SL). at the ?- prompt on the right, and step with Creep (or Enter), except in three places: at the call to partition/4 and at each of the two recursive calls to qsort_dl_/2 press Skip, which runs the call to its end without showing what happens inside it.
:- module(qs,_).
%! \begin{miniplayground}
qsort_dl(L,SL) :-
qsort_dl_(L,SL-SLE),
SLE = [].
qsort_dl_([],SLE-SLE).
qsort_dl_([X|L],SL-SLE) :-
partition(L,X,S,B),
qsort_dl_(S,SS-SSE),
qsort_dl_(B,BS-BSE),
SSE = [X|BS],
SL = SS,
SLE = BSE.
partition([],_P,[],[]).
partition([E|R],P,[E|Smalls],Bigs) :-
E < P,
partition(R,P,Smalls,Bigs).
partition([E|R],P,Smalls,[E|Bigs]) :-
E >= P,
partition(R,P,Smalls,Bigs).
%! \end{miniplayground}The whole trace is then eighteen lines. The two recursive calls exit with [1,2,3|_A]-_A and [6,7|_B]-_B (the debugger prints the variables with numbers, such as _29837): each sorted list ends in a variable, and that same variable is the second part of the pair. Then come the three unifications, as calls to =/2, and in each of them we see what is being connected: the first one is entered with _A and [5,6,7|_B]; the second one with the variable of the result and [1,2,3,5,6,7|_B], since the small ones now continue into the pivot and the big ones; and the third one with the two ends. The clause exits with the pair [1,2,3,5,6,7|_C]-_C, and the last unification, SLE = [], closes the list.Version 2 — the same program, still with the -/2 functor, but with the unifications moved into the head and the arguments, where they belong:
:- module(_,_).
qsort_dl(L,SL) :-
qsort_dl_(L,SL-[]).
%
qsort_dl_([],SLE-SLE).
qsort_dl_([X|L],SL-SLE) :-
partition(L,X,S,B),
qsort_dl_(S,SL-[X|BS]),
qsort_dl_(B,BS-SLE).partition([],_P,[],[]). partition([E|R],P,[E|Smalls],Bigs) :- E < P, partition(R,P,Smalls,Bigs). partition([E|R],P,Smalls,[E|Bigs]) :- E >= P, partition(R,P,Smalls,Bigs).
?- qsort_dl([5,2,1,3,7,6], SL).Expected answer:
SL = [1,2,3,5,6,7] ?The explicit =/2 goals have vanished into the argument positions. qsort_dl_(S,SL-[X|BS]) says in one term: sort S into the front of SL, and let its tail be the pivot followed by whatever BS turns out to be.
This can be watched as well. The program in the debugger box above can be edited, and the next query runs the edited program: change its qsort_dl/2 and qsort_dl_/2 into the ones of this version and step through the same query in the same way. The call for the small ones is now entered as qsort_dl_([2,1,3],SL-[5|BS]), with the pivot already in place at the end before anything is sorted, and it exits with [1,2,3,5|BS]-[5|BS]. The trace is ten lines: the eight of the unifications are gone. (The same can be done with version 3, below.)
Version 3 — we drop the -/2 functor and use two arguments instead:
:- module(_,_).
qsort_dl(L,SL) :-
qsort_dl_(L,SL,[]).
%
qsort_dl_([],SLE,SLE).
qsort_dl_([X|L],SL,SLE) :-
partition(L,X,S,B),
qsort_dl_(S,SL,[X|BS]),
qsort_dl_(B,BS,SLE).partition([],_P,[],[]). partition([E|R],P,[E|Smalls],Bigs) :- E < P, partition(R,P,Smalls,Bigs). partition([E|R],P,Smalls,[E|Bigs]) :- E >= P, partition(R,P,Smalls,Bigs).
?- qsort_dl([5,2,1,3,7,6], SL).Expected answer:
SL = [1,2,3,5,6,7] ?The -/2 was only ever notation; two plain arguments carry the same pair, and one term construction per call is saved. In fact the - version is slightly more expensive, since it builds a structure that nothing needs.
This shape is worth remembering — a pair of arguments, one for the list and one for its tail — because it is exactly what the section on grammars is about.
The goal of this section is to parse the plane flies — and to arrive at a notation in which the program is the grammar. We get there in four steps, each one a mechanical improvement on the previous one.
:- module(_,_).
% :- use_package(sr/bfall).
myphrase(P) :-
% An article (A) must be at beginning of P, T1 is the rest:
append_(A,T1,P), article(A),
append_(S1,T2,T1), spaces(S1), % Spaces must follow
append_(N,T3,T2), noun(N), % A noun must follow
append_(S2,V,T3), spaces(S2), % Spaces must follow
verb(V). % Must end with a verb
article([a]).
article([t,h,e]).
spaces([' ']).
spaces([' ' | T]) :-
spaces(T).
noun([c,a,r]).
noun([p,l,a,n,e]).
verb([f,l,i,e,s]).
verb([d,r,i,v,e,s]).
% - Local version for alternate search rule
append_([],X,X).
append_([X|Y],Z,[X|W]) :- append_(Y,Z,W).(append_/3 is the usual definition of append; having our own copy in the file will allow us to change the search rule for the whole program below.)?- myphrase([t,h,e,' ',p,l,a,n,e,' ',f,l,i,e,s]).Expected answer:
yes
?- myphrase([t,h,e,' ',p,l,a,n,e]).Expected answer:
noA grammar is a description of the syntax of the phrases that we want to recognize — formally similar to the automata that we programmed in pure logic programming, but richer and higher-level. Words are represented as lists of letters: a is [a], "the" is [t,h,e]. Spaces are one or more, which is an ordinary two-clause recursion.
How does it work? append_(A,T1,P), run backwards, splits the phrase into a first part A and the rest, T1, and article(A) checks that the first part is an article. Then the same is done with T1, and so on down the phrase. append_/3 is being used to subtract a piece off the front.
A leading space is rejected — nothing in the grammar allows one:
?- myphrase([' ',t,h,e,' ',p,l,a,n,e,' ',f,l,i,e,s]).Expected answer:
noBut extra spaces inside are fine, because spaces/1 is recursive:
?- myphrase([a,' ',' ',p,l,a,n,e,' ',d,r,i,v,e,s]).Expected answer:
yes
Every alternative in the grammar is a clause, and every backtrack is Prolog doing what it does anyway.
It works, and it is generate and test: append_/3 proposes every possible split of the list, and article/1 and the rest reject the bad ones. Every split of every remaining tail — the cost is appalling, and there are four calls to append_/3.
And since it is a logic program, it can also generate phrases:
?- myphrase(X).Expected answer:
X = [a,' ',c,a,r,' ',f,l,i,e,s] ? ; X = [a,' ',c,a,r,' ',d,r,i,v,e,s] ? ; X = [a,' ',c,a,r,' ',' ',f,l,i,e,s] ? ; X = [a,' ',c,a,r,' ',' ',d,r,i,v,e,s] ?With depth-first search the enumeration gets stuck in the recursive clause of spaces/1: it keeps adding spaces before the verb, and never gets to the plane. To see the whole language come out, uncomment the :- use_package(sr/bfall). line in the program above (which makes it run breadth-first), press its ▶ to load it again, and repeat the query. The generation is then fair:
X = [a,' ',c,a,r,' ',f,l,i,e,s] ? ; X = [a,' ',c,a,r,' ',d,r,i,v,e,s] ? ; X = [a,' ',c,a,r,' ',' ',f,l,i,e,s] ? ; X = [a,' ',c,a,r,' ',' ',d,r,i,v,e,s] ? ; X = [a,' ',p,l,a,n,e,' ',f,l,i,e,s] ? ; X = [a,' ',p,l,a,n,e,' ',d,r,i,v,e,s] ? ; X = [a,' ',' ',c,a,r,' ',f,l,i,e,s] ? ; X = [a,' ',' ',c,a,r,' ',d,r,i,v,e,s] ? ; X = [t,h,e,' ',c,a,r,' ',f,l,i,e,s] ?
:- module(_,_).
% :- use_package(sr/bfall).
myphrase(P,C) :-
% Article is beginning of phrase, rest is beginning of spaces
article(P,CA), spaces(CA,CS1),
noun(CS1,CN), spaces(CN,CS2),
verb(CS2,C).
article([a|T],T).
article([t,h,e|T],T).
spaces([' ' | T],T).
spaces([' ' | Y],T) :-
spaces(Y,T).
noun([c,a,r | T],T).
noun([p,l,a,n,e | T],T).
verb([f,l,i,e,s | T],T).
verb([d,r,i,v,e,s | T],T).?- myphrase([t,h,e,' ',p,l,a,n,e,' ',f,l,i,e,s|T], T).Expected answer:
yesEvery append_/3 is gone. article([t,h,e|T],T) says if the input starts with the, the remainder is T — a fact, matched by head unification alone, in constant time.
This is the difference-list pair that we used in quicksort, doing a completely different job. The chaining of the variables — P to CA to CS1 to CN to CS2 to C — is the sequencing of the grammar.
We can also call it with a closed list, with [] as the second argument, which says "and there must be nothing left over":
?- myphrase([t,h,e,' ',p,l,a,n,e,' ',f,l,i,e,s], []).Expected answer:
yes
?- myphrase([t,h,e,' ',p,l,a,n,e], []).Expected answer:
noThis is the better way of calling it, because it behaves better in case of failure. With an open list the incomplete phrase is not rejected: the open tail is instantiated to complete it, and (the tail being also the remainder) the result is a cyclic term:
?- myphrase([t,h,e,' ',p,l,a,n,e|T], T).Expected answer:
T = [' ',f,l,i,e,s|T] ?And we can generate in both forms:
?- myphrase(X, T).Expected answer:
X = [a,' ',c,a,r,' ',f,l,i,e,s|T] ? ; X = [a,' ',c,a,r,' ',d,r,i,v,e,s|T] ? ; X = [a,' ',c,a,r,' ',' ',f,l,i,e,s|T] ?
?- myphrase(X, []).Expected answer:
X = [a,' ',c,a,r,' ',f,l,i,e,s] ? ; X = [a,' ',c,a,r,' ',d,r,i,v,e,s] ? ; X = [a,' ',c,a,r,' ',' ',f,l,i,e,s] ?(Again, the generation is only fair with the :- use_package(sr/bfall). line uncommented.)
:- module(_,_).
% :- use_package(sr/bfall).
myphrase(P,C) :-
article(P,CA), spaces(CA,CS1),
noun(CS1,CN), spaces(CN,CS2),
verb(CS2,C).and for the rest we use the || operator, which does for strings what | does for lists: what follows it is the tail of the list.article( "a" || T, T). % Translates to article( [ 97|T], T). % i.e., article( [0'a|T], T). article( "the" || T, T). % Translates to article( [0't,0'h,0'e|T], T). spaces( " " || T, T). spaces( " " || Y, T) :- spaces(Y, T). noun( "car" || T, T). noun( "plane" || T, T). verb( "flies" || T, T). verb( "drives" || T, T).
?- myphrase("the plane flies", []).Expected answer:yes
?- myphrase("the plane", []).Expected answer:noNothing changed but the notation. "the" || T is exactly [t,h,e|T], with the characters as codes. So, when generating, the phrases are printed as lists of codes:
?- myphrase(S, []).Expected answer:
S = [97,32,99,97,114,32,102,108,105,101,115] ?unless we turn on the flag that makes the top level print such lists as strings. We leave it on from now on:
?- set_prolog_flag(write_strings, on).Expected answer:
yes
?- myphrase(S, []).Expected answer:
S = "a car flies" ? ; S = "a car drives" ? ; S = "a car flies" ?
So we let the system add them. That syntactic transformation is what a definite clause grammar (DCG) is: --> is a macro that expands into the threaded two-argument version.
:- module(_,_). :- use_package(dcg). % :- use_package(sr/bfall). myphrase --> article, spaces, noun, spaces, verb. article --> "a". article --> "the". spaces --> " ". spaces --> " ", spaces. noun --> "car". noun --> "plane". verb --> "flies". verb --> "drives".That is a grammar. Read it aloud: a phrase is an article, spaces, a noun, spaces and a verb.
?- myphrase("the plane flies", []).Expected answer:yesNote that the query passes two arguments — because what is really being called is the expanded version; the arrow put them there. We can also use the phrase/2 built-in, which supplies the [] for us:
?- phrase(myphrase,"the plane flies").Expected answer:
yes
?- myphrase("the plane", []).Expected answer:no
?- myphrase(S, []).Expected answer:
S = "a car flies" ? ; S = "a car drives" ? ; S = "a car flies" ?The same lines that recognize sentences also produce them, on backtracking. A parser generator in another language gives a recognizer; here we get the relation.
(Under depth-first search the enumeration gets stuck in the recursive spaces rule, as before. With the :- use_package(sr/bfall). line uncommented, and the program loaded again, the answers are "a car flies", "a car drives", "a car flies", "a plane flies", "a car flies", "the car flies", ...)
What the translation produces. The --> clauses are translated into exactly the two-argument predicates that we wrote by hand before. Here is the same grammar again, with the translation in the comments:
:- module(_,_). :- use_package(dcg). % :- use_package(sr/bfall). myphrase --> article, spaces, noun, spaces, verb. % Translates to: % myphrase(X,C) :- article(X,CA), spaces(CA,CS1), noun(CS1,CN), % spaces(CN,CS2), verb(CS2,C). article --> "a". % Translates to (*): article( "a" || X, X). article --> "the". spaces --> " ". spaces --> " ", spaces. noun --> "car". noun --> "plane". verb --> "flies". verb --> "drives".
?- myphrase("the plane flies", []).Expected answer:yesNothing new is happening; the arguments are merely implicit.
We can intersperse additional actions within the grammar:
:- module(_,_).
:- use_package(dcg).
% :- use_package(sr/bfall).
myphrase(N) --> article(AC), spaces(S1), noun(NC), spaces(S2),
verb(VC), { N is AC + S1 + NC + S2 + VC }.
% Translates to:
% myphrase(N,X1,X6) :- article(AC,X1,X2), spaces(S1,X2,X3), noun(NC,X3,X4),
% spaces(S2,X4,X5), verb(VC,X5,X6), N is AC+S1+NC+S2+VC.
article(1) --> "a".
article(3) --> "the".
spaces(1) --> " ".
spaces(N) --> " ", spaces(N1), { N is N1+1 }.
noun(3) --> "car".
noun(5) --> "plane".
verb(5) --> "flies".
verb(6) --> "drives".?- myphrase(NChars, "the plane flies", []).Expected answer:
NChars = 15 ?Or, using phrase/2:
?- phrase(myphrase(NChars), "the plane flies").Expected answer:
NChars = 15 ?Fifteen characters: 3 + 1 + 5 + 1 + 5.
?- myphrase(NChars, "the plane", []).Expected answer:
noLet us read the rules. article(1) --> "a". says an article may be a, and it has one character. The spaces rule is the pretty one: one space has one character; and a space followed by more spaces, which have N1 characters, has N1 + 1 — with { N is N1+1 } being plain Prolog dropped into the middle of a grammar rule. So spaces really has three arguments: the additional one carrying the count, and the two hidden ones doing the difference-list threading.
The counts travel in that additional argument, and a final { ... } adds them up. Which is exactly how we would build an abstract syntax tree as we parse, or compute a value, or check a context condition — the grammar and the semantic actions live in the same notation.
And it still generates, now with the count of each phrase:
?- myphrase(NChars, S, []).Expected answer:
NChars = 11, S = "a car flies" ? ; NChars = 12, S = "a car drives" ? ; NChars = 12, S = "a car flies" ?
Repeat loops and failure-driven loops. The pattern is worth recognizing, because it is what imperative Prolog looks like:
main(_) :- repeat, read(X), process(X). process(end). process(X) :- display(X), nl, fail.repeat/0 succeeds infinitely often on backtracking, and fail/0 drives the loop round again — so this reads a term, prints it, fails back into repeat, and reads the next, until end arrives and the first clause of process/1 stops the loop. It is a while loop built out of backtracking.
Also: exception handling; extending the syntax beyond operators with term expansions and macros, which is what a package is; delay declarations and concurrency; the operating system interface, sockets; foreign language interfaces such as C; and a great many more built-ins.
| Arrays | Assoc | Attributes | Heaps |
|---|---|---|---|
| Lists | Term Utilities | Ordset | Queues |
| Random | System Utilities | Tree | UGraphs |
| WGraphs | Sockets | Linda/Distribution | Persistent DB |
| CLPB | CLPQR | CLPFD | Objects |
| GCLA | TclTk | Tracing | Chars I/O |
| Runtime Utilities | Timeout | Xrefs | WWW |
| Java Interface | ... | ... | ... |
Other execution rules. Breadth-first, iterative deepening, random; tabling; CASP (negation with multiple models); Andorra ("determinate-first") execution; fuzzy Prolog. We have used one of these all along — sr/bfall — so the mechanism is already familiar.
Interfaces to other languages and systems. C, Java, JavaScript, Python, LLVM; an SQL database interface and persistent predicates; web, HTML, XML and CGI programming (PiLLoW), HTTP connectivity, JSON, compilation to JavaScript; interfaces to solvers (PPL, Mathematica, MiniSAT, Z3, Yices); Graphviz and daVinci; Electron, wxWidgets, Tcl/Tk, VRML.
Syntactic and semantic extensions. Functional notation and higher order — both of which we have used; terms with named arguments (records and feature terms); multiple argument indexing; the script interpreter; active modules for high-level distributed execution; concurrency and multithreading; attributed variables; object-oriented programming.
Constraint programming. Rationals, reals, finite domains; CHR (constraint handling rules), Gecode. Constraints have their own part of the course, and they are where the arithmetic that we lost with is/2 comes back — declarative and efficient.
Assertions, which we used twice as a way of stating what a predicate expects: regular types, modes, determinacy and other properties; run-time checking; assertion-based unit tests and automatic test case generation; and compile-time property inference and assertion checking with CiaoPP.
Additional programming support. Automatic documentation (LPdoc — which produced this document); partial evaluation, optimization and parallelization (CiaoPP).
Sometimes that is exactly the right trade. The part of the course on constraints shows that for arithmetic, at least, it was never necessary.