Computer Science 170
Analysis of Programming Languages

Spring 2003, Clark University
D Joyce


Prolog example

The GNU Prolog web site is at http://pauillac.inria.fr/~diaz /gnu-prolog/. It includes a manual at http://pauillac.inria.f r/~diaz/gnu-prolog/manual/. Start reading the manual at the section entitled "The GNU Prolog interactive interpreter."

Here's an example session.

$ gprolog
GNU Prolog 1.2.7

| ?- consult(user).
 first(A,X)  :- append([A],_,X).
 second(B,X) :- append([_,B],_,X).
 final(Z,X)  :- append(_,[Z],X).
 nexttolast(Z,X) :- append(_,[Z,_],X).
 triple(X)   :- append(A,B,X),
                append(A,A,B).
[ctrl/D]

| ?- first(3,[3,4]).
Yes
| ?- first(3,[4,3]).
No
| ?- first(X,[3,4]).
X=3
Yes

| ?- second(3,[2,3,4]).
Yes
| ?- second(3,[3,4,5]).
No

| ?- final(3,[1,2,3]).
Yes
| ?- final(3,[3,2,1]).
No

| ?- triple([3,4,3,4,3,4]).
Yes
| ?- triple([3,3,4]).
No

| ?- consult(user).
 insert(Y,A,X) :- append(B,C,Y),
                    append(D,C,X),
                    append(B,[A],D).
[ctrl/D]

| ?- insert([1,3],2,[1,2,3]).
Yes
| ?- insert([1,3],2,[1,2,4]).
No
| ?- insert([1,3],X,[1,2,3]).
X = 2
Yes
| ?- insert([1,2],X,[1,2,3]).
X = 3
Yes
| ?- insert([1,1],X,[1,1,1]).
X = 1;
X = 1;
X = 1;
No
| ?- insert(X,2,[1,2,3,2,4]).
X = [1,3,2,4];
X = [1,2,3,4];
ERROR: Out of global stack


Minor points. No space between consult and (user). If you enter | ?- consult (user). you'll get an "uncaught exception" meaning a syntax error on that line. Just enter the correct statement next. To exit prolog, enter ctrl/c, then enter e.