Docsity

Logic Programming with Prolog: Lecture Notes by Tevfik Koşar, Study notes of Programming Languages

Partial preview of the text

Download Logic Programming with Prolog: Lecture Notes by Tevfik Koşar and more Study notes Programming Languages in PDF only on Docsity!

1

Programming Languages

Tevfik Koşar

Lecture - XIX March 28th, 2006

2

Roadmap

  • Logic Languages
    • Predicate Calculus
  • Prolog Programming Language
    • Basics
    • Queries
    • Resolution
    • Unification
    • Lists
    • Running Prolog Programs

3

Logic Programming

  • Based on predicate calculus
    • (Functional lang. were based on Lambda Calculus)
  • Predicates - building-blocks P(a 1 ,a 2 ,...,aK)
    • Define relationships between entities
  • Eg:
    • enrolled(john, cs4101)
    • taught_by(cs4101, dr_kosar)

4

Logic Programming

  • Axioms: define logic rules between predicates
  • H  B 1 , B 2 , B 3 , ….. Bn
  • Eg:
    • takes_class_from(X,Y)  enrolled (X,Z), taught_by(Z,Y)
    • enrolled(john, cs4101)
    • taught_by(cs4101, dr_kosar)

 takes_class_from(john, dr_kosar)

7

Prolog

  • Prolog predicates/facts:
    • rainy(baton_rouge).
    • teaches(dr_kosar, csc4101).
    • Predicates/clauses end with ‘.’
    • Predicates are called facts, and axioms are called rules
  • Prolog axioms/rules:
    • snowy(X) :- rainy(X), cold(X).
    • ‘:-’ is the implication symbol
    • ‘,’ indicates ‘and’.

8

Prolog Queries

rainy(seattle).

rainy(newyork).

?- rainy(X).

X = seattle;

X = newyork;

no

9

Prolog Queries

rainy(seattle).

rainy(rochester).

cold(rochester).

snowy(X) :- rainy(X), cold(X).

?- snowy(X).

X = rochester;

no

10

Resolution

  • C  A, B
  • D  C

  • Resolution: D  A, B
  • takes (jane, csc4101).
  • classmates(X,Y) :- takes(X,Z), takes(Y,Z).

  • Resolution: classmates(jane, Y) :- takes(Y, csc4101)

13

Unification

  • takes_lab(S) :- takes(S, C), has_lab(C).
  • has_lab(D) :- meets_in(D, R), is_lab(R).

 takes_lab(S) :- takes(S, C), meets_in(C, R), is_lab(R).

14

Lists

  • [a, b, c] can be expressed as (using vertical bar notation):
    • [a | [b, c]]
    • [a, b | [c]]
    • [a, b, c | []]
  • member(X, [X|T]).
  • member(X, [H|T]) :- member(X, T).
  • sorted([]).
  • sorted([X]).
  • sorted([A, B | T]) :- A <= B, sorted([B | T]).

15

Lists

append([], A, A). append(H | T), A, [H | L]) :- append(T, A, L).

?- append([a, b, c], [d, e], L). L = [a , b, c, d, e] ?- append(X, [d, e], [a, b, c, d, e]). X = [a, b, c] ?- append([a, b, c], Y, [a, b, c, d, e]). Y = [d, e]

 Prolog predicates do not have a clear distinction between input and output arguments!

16

Arithmetic

  • Built-in is predicate: unifies its first argument with the arithmetic value of its second argument.

?- is(X, 1+2). X = 3 ?- X is 1+2. X = 3 ?- 3 is 1+2. yes ?- 1+2 is 3. no ?- X is Y. ?- Y is 1+2, X is Y. X = 3 Y = 3