Docsity

Lecture Notes on Prolog: Lists and Operators (CPSC 326, Spring 2013), Study notes of Programming Languages

Partial preview of the text

Download Lecture Notes on Prolog: Lists and Operators (CPSC 326, Spring 2013) and more Study notes Programming Languages in PDF only on Docsity!

Today ...

  • Lists (cont.)
  • Arithmetic operators

More examples of lists ...

  • consider a prefix predicate

prefix([1,2], [1,2,3,4])

  • we can write this w/out reusing variables:

prefix([], _). prefix([X|T1], [Y|T2]) :- X = Y, prefix(T1, T2).

  • or using shared variables:

prefix([], _). prefix([X|T1], [X|T2]) :- prefix(T1, T2).

We can use append to define a reverse predicate

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

Q: What is the proof tree for reverse([1,2], A)?

Q: What happens if the goal is reverse(X, [1,2])?

  • Hint: Draw the proof tree ...
  • The “signature” for reverse is: reverse(+List1, -List2)
  • Note that List2 can also be instantiated

How can we define reverse(?List1, ?List2)?

reverse(Xs, Ys) :- reverse(Xs, [], Ys, Ys).

reverse([], Ys, Ys, []). reverse([X|Xs], Rs, Ys, [_|Bound]) :- reverse(Xs, [X|Rs], Ys, Bound).

Here we distinguish reverse/2 from reverse/

  • in general, functor/arity “identifies” the predicate

Operators

Prolog supports standard arithmetic operators

  • But beware the definition of = (unifies)

?- X = 2 + 3. X = 2+

?- X = 2 * 3 + 4. X = 2*3+

  • These are not being evaluated!
  • Use “is” to evaluate expressions ...

?- X is 2 + 3. X = 5

?- X is 2 * 3 + 4. X = 10

  • Real and integer division

?- X is 7/2. % real division X = 3.

?- X is 7//2. % integer division X = 3

?- X is 7 mod 2. X = 1

Using Operators

Calculating the length of a list

length([], 0). length([_|T], N) :- length(T, N1), N is 1 + N1.

Q: What is the proof tree for length([1,2,3], N)?

Additional comparison operators

true

?- 3 =< 4. true.

?- 3 > 4. false.

?- 4 >= 4. true.

?- X > 4. ERROR: >/2: Args not sufficiently instantiated