Programming Language Design Paradigms: Logic Programming: Part 2 - Semantics
Programming Language Design Paradigms: Logic Programming: Part 2 - Semantics
Programming Language Design Paradigms: Logic Programming: Part 2 - Semantics
Department of Informatics
Kings College London
Spring 2017
Introduction
{s1 = t1 , . . . , sn = tn }
(3) X = X,E E
(4) t = X,E X = t, E
if t is not a variable
(5) X = t, E X = t, E {X 7 t}
if X not in t and X in E
(6) X = t, E failure
if X in t and X 6= t
More on the unification algorithm
Example
{ f(a, a) = f(X, a) }
I using rule (1) with the first equation:
{a = X , a = a}
I using rule (4) with the first equation:
{X = a, a = a}
I using rule (1) with the second equation:
{X = a}
{X 7 a}
More examples of unification
Example
{[X | L] = [0], Y = [1, 2], [X | Z] = U}
I using rule (1) with the first equation:
{X = 0, L = [], Y = [1, 2], [X | Z] = U}
I using rule (5) with the first equation:
{X = 0, L = [], Y = [1, 2], [0 | Z] = U}
I using rule (4) with the last equation:
{X = 0, L = [], Y = [1, 2], U = [0 | Z]}
{X 7 0, L 7 [], Y 7 [1, 2], U 7 [0 | Z]}
Exercise
{X 7 g (a), Z 7 a}
The Principle of Resolution
goal
mgu
resolvent
Example
based(prolog, logic).
based(haskell, maths).
likes(max, logic).
likes(claire, maths).
likes(X, P) :- based(P, Y), likes(X, Y).
Example of SLD-resolution in Prolog continued
Example
I :- likes(Z, prolog).
I Using the last clause and the mgu {X 7 Z, P 7 prolog}, we
obtain the resolvent :- based(prolog, Y), likes(Z, Y).
I Now using the first clause and the mgu {Y 7 logic}, we
obtain the new resolvent :- likes(Z, logic).
I Since we can now unify with the fact likes(max, logic).
using the substitution {Z 7 max}, we can obtain an empty
resolvent
I The composition of substitutions generated is
{X 7 max, P 7 prolog, Y 7 logic, Z 7 max}
I And the solution to the initial query is {Z 7 max}
Example of SLD-resolution in Prolog continued
Example
:- likes(Z, prolog).
{X 7 Z, P 7 prolog}
{Y 7 logic}
:- likes(Z, logic).
{Z 7 max} {X 7 Z, P 7 logic}
Example
:- likes(Z, painting).
{X 7 Z, P 7 painting}
Example
append([], L, L).
append([X | L], Y, [X | Z]) :- append(L, Y, Z).
Example
:- append(X, [1, 2], U).
{L1 7 [], Z1 7 [1, 2]} {L1 7 [X2 | L2], Z 7 [X2 | Z2], Y2 7 [1, 2]}
.
.
.
Example of non-termination
Since Prolog searches the tree using the program clauses in the
order in which they are written, and in a depth-first manner, it is
important to put base clauses before recursive clauses.
Example
append([X|L],Y,[X|Z]) :- append(L,Y,Z).
append([],L,L).
Example
..
.
Exercise
length([], 0).
length([H | T], N) :- length(T, M), N is 1 + M.
{H 7 2, T 7 [3 | []], X 7 N}
{H1 7 3, T1 7 [], N1 7 M}
{M1 7 0}
:- M is 1 + 0, N is 1 + M.
{M 7 1}
:- N is 1 + 1.
{N 7 2}