Lecture: Introduction to Logic Programming

Background Material



Logic programming consists of a set of declarations (things that are true) and inference rules. A logic program is executed by running queries against the program. Most logic programming languages incorporate unifcation and backtracking. Clauses in a logic program can be viewed as specifications. E.G. (using prolog notation)
  1. gcd(U,0,U).
  2. gcd(U,V,W) :- V=\=0, R is U mod V, gcd(V,R,W).
  3. append([],Y,Y).
  4. append([X|XS],Y,[X|ZS]) :- append(XS,Y,ZS).
  5. sort(X,Y) :- permutation(X,Y), sorted(Y).
Given a control mechanism (inference rule), these specifications can be turned into programs that sort a list and compute the greatest common divisor of two integers.


  1. Horn clauses and queries.

    A Horn claus is a statement of the form a_1 and a_2 and ... and a_n &rarr b. In prolog is is written b :- a1,a2,...,an. b is called the head, and a_1,a_2,...,a_n the body. A clause without a body is always true and is called an axiom or fact. A Horn clause without a head is considered a query or goal.

    1. ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y).
    2. ancestor(X,X).
    3. parent(amy,bob).
    Consider the following queries.
    1. ?- parent(amy,bob).
    2. yes
    3. ?- ancestor(amy,bob).
    4. true ?
    5. yes
    6. ?- ancestor(bob,amy).
    7. no
    8. ?- ancestor(X,bob).
    9. X = amy ? ;
    10. X = bob
    11. yes
  2. Arithmetic.
    1. is predicate.
    2. X is 3+4*5.
    3. is(X,3+4*5).
  3. Resolution and unification.

    If we have Horn clauses a &larr a_1,...,a_n. and b &larr b_1,...,b_m. and b_i matches a, then we can infer the clause b &larr b_1,...,b_{i-1},a_1,...,a_n,b_{i+1},...,b_m. In the case when there is only a single statement in the body: b &larr a. and c &larr b, then we infer c &larr a.

    In order to match statements it may be necessary to instantiate variables. This process is called unification.

    1. legs(x,2) &larr mammal(x), arms(x,2).
    2. legs(x,4) &larr mammal(x), armx(x,0).
    3. mammal(horse).
    4. arms(horse,0).
    Now perform resolution on the queries
    1. legs(horse,4).
    2. legs(horse,Y).
  4. Backtracking.
  5. Lists.

Lecture Notes

Sample Programs



Created: May 28, 2008 (revised May 26, 2010) by jjohnson AT cs DOT drexel DOT DOT edu