Addition Problems in Prolog
The following Prolog code defines addition in two different ways, and then
shows the results of executing it. See Notes on
using BinProlog 4.00 for more on the language.
/* /net/cat/disk1/prolog/exs/addn.pl */
/* addition */
add(X,0,X).
add(X,s(Y),Z) :- add(s(X),Y,Z).
q1 :- add(s(0), 0, s(0)).
q1(Z) :- add(s(0), 0, Z).
q2 :- add(s(0), s(0), s(s(0))).
q2(Z) :- add(s(0), s(0), Z).
q3 :- add(s(s(0)), s(s(0)), s(s(s(s(0))))).
q3(Z) :- add(s(s(0)), s(s(0)), Z).
q4(X) :- add(X, s(s(0)), s(s(s(s(0))))).
q5(Y) :- add(s(s(0)), Y, s(s(s(s(0))))).
addn(X,0,X).
addn(X,s(Y),Z) :- addn(s(X),Y,Z),!.
qn1 :- addn(s(0), 0, s(0)).
qn1(Z) :- addn(s(0), 0, Z).
qn2 :- addn(s(0), s(0), s(s(0))).
qn2(Z) :- addn(s(0), s(0), Z).
qn3 :- addn(s(s(0)), s(s(0)), s(s(s(s(0))))).
qn3(Z) :- addn(s(s(0)), s(s(0)), Z).
qn4(X) :- addn(X, s(s(0)), s(s(s(s(0))))).
qn5(Y) :- addn(s(s(0)), Y, s(s(s(s(0))))).
Below is a transcript on a session running the queries in this example.
(Notice that the way carriage returns are inserted is not very nice; I guess
the designers of the language never took a good course in user interface
design.) What BinProlog does to the query "q5(X)." is a rather
sophisticated process called narrowing; you might want to try
"trace(q5(X))." to see what is happening.
awk% bp
BinProlog 4.00 Copyright (C) Paul Tarau 1992-1995
by FTP from: clement.info.umoncton.ca
E-MAIL to : binprolog@info.umoncton.ca
(C-ified standalone)
(with heap GC enabled)
Finished loading system C-code (23203 instructions).
Finished loading user C-code (4 instructions).
?- consult(addn).
% using compile/1 is MUCH faster
consulting(addn.pl)
consulted(addn.pl,time(16))
yes
?- q1.
yes
?- q2.
yes
?- q2(X).
X=s(s(0));
no
?- q3.
yes
?- q3(X).
X=s(s(s(s(0))));
no
?- q4(X).
X=s(s(0));
no
?- q5(X).
X=s(s(0));
warning: *** copy_term overflow in findall_store_heap ***
warning: *** overflow in findall_store_heap ***
?- qn1.
yes
?- qn2.
yes
?- qn2(X).
X=s(s(0));
no
?- qn3.
yes
?- qn3(X).
X=s(s(s(s(0))));
no
?- qn4(X).
X=s(s(0));
no
?- qn5(X).
X=s(s(0));
no
?- halt.
Prolog execution halted(0). CPU time = 0.250s
awk%
Thanks to Kai Lin for help with this example.
Back to CSE 230 homepage
Maintained by Joseph Goguen
© 2000, 2001 Joseph Goguen
Last modified: Sat Feb 23 11:47:00 PST 2002