Download Programming in Pure Prolog

Transcript
124 Programming in Pure Prolog
The following interaction with a Prolog system shows that these simplifications
are also carried out internally. Here =/2 is Prolog’s built-in written using the infix
notation (that is, between the arguments) and defined internally by a single clause:
% X = Y ← X and Y are unifiable.
X = X.
| ?- X = [a | [b | c]].
X = [a,b|c]
| ?- [a,b|c]
= [a | [b | c]].
yes
| ?- X = [a | [b, c | []]].
X = [a,b,c]
| ?- [a,b,c] = [a | [b, c | []]].
yes
To enhance the readability of the programs that use lists we incorporate the
above notation and abbreviations into pure Prolog.
The above abbreviations easily confuse a beginner. To test your understanding
of this notation please solve the following exercise.
Exercise 59 Which of the following terms are lists:
[a,b], [a|b], [a|[b|c]], [a,[b,c]], [a,[b|c]], [a|[b,c]]?
2
Further, to enhance the readability, we also use in programs the names ending
with “s” to denote variables which are meant to be instantiated to lists. Note that
the elements of a list need not to be ground.
We now present a pot-pourri of programs that use lists.
List
The definition of lists directly translates into the following simple program which
recognizes whether a term is a list:
% list(Xs) ← Xs is a list.
list([]).
list([ | Ts]) ← list(Ts).
Program: LIST