Computing the sum of the elements of an integer list in Java.
int sum (int[] list) {
int result = 0;
for (int i = 0; i < list.length; i++)
result += list[i];
return result;
}
Computing the sum of the elements of an integer list in OCaml.
let rec sum l = match l with
| [] -> 0
| x::xs -> x + sum xs
Computing the sum of the elements of an integer list in Prolog.
sum([],0).
sum([H | T], N) :- sum(T,M), N is H+M.
Notice that this is a declarative reading of the sum of a list.
+-----------------+
Queries ==> | Facts + Rules | ==> Answers
+-----------------+
Prolog Program
Facts and rules together build up a database of relations.
The program
sum([],0)
sum([H | T], N) :- sum(T,M), N is M+H
inductively defines a table of relations:
+-------------+
| List | Sum |
|-------|-----|
| [] | 0 |
| [1] | 1 |
| [1,2] | 3 |
| [2] | 2 |
| ... | ... |
?- sum([1,2,3],X).
Of course, the computation model is not to build a database and look up facts.
Prolog = Logic (programmer) + Control (compiler)
Prolog programs are made up of terms.
father(rickard,ned).
father(rickard,brandon).
father(rickard,lyanna).
father(ned,robb).
father(ned,sansa).
father(ned,arya).
?- father(ned,sansa).
?- father(rickard,sansa).
?- father(ned,bran).
false
for everything else."Who are Ned's children?"
?- father(ned, X).
"Who is the father of Arya?"
?- father(X,arya).
"Who are Robb's children?"
?- father(robb,X).
H :- B1, B2, B3, ..., BN
parent(X,Y) :- father(X,Y).
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y).
Observe that Z
only appears on the RHS of the last rule.
?- ancestor(rickard,X).
parent(X,Y) :- father(X,Y).
ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y).
Define mother, cousin, uncle, aunt, sibling.
material(gold).
material(aluminium).
process(bauxite,alumina).
process(alumina,aluminium).
process(copper, bronze).
valuable(X) :- material(X).
valuable(X) :- process(X,Y), valuable(Y).
?- valuable(gold).
?- valuable(bauxite).
?- valuable(bronze).
?- valuable(copper).
At the core of how Prolog computes is Unification.
There are 3 rules for unification:
Which of these unify?
A. tree(l,r) & tree(B,C)
B. tree(A,r) & tree(l,C)
C. A & a(A)
D. a & a(A)
Which of these unify?
A. tree(l,r) & tree(B,C) yes
B. tree(A,r) & tree(l,C) yes
C. A & a(A) yes (mostly), occurs check disabled by default
D. a & a(A) no