Here are some Prolog programs (written in Strawberry Prolog) and their output:
program
father(avraham, yitzchak).
father(yitzchak, yaakov).
ancestor(X, Y) :- father(X,Y).
ancestor(X, Y) :- father(X,Z), ancestor(Z, Y).
?- father(yitzchak, X), write(X), write("\n").
Output:
Compiling the file:
c:\father
0 errors, 0 warnings.
yaakov
Yes.
program
add1(X, Y) :- Y is X + 1.
?- add1(4, 5).
output
Yes.
program
add1(X, Y) :- Y is X + 1.
?- add1(4, 6).
output
No.
program
add1(X, Y) :- Y is X + 1.
?- add1(4, X), write(X), write("\n").
output
5
Yes.
program
add(X, Y, Z) :- Z is X + Y.
?- add(4, 5, X), write(X), write("\n").
output
9
Yes.
program
add(X, Y, Z) :- Z is X + Y.
?- add(4, "hello", X), write(X), write("\n").
output
4hello
Yes.
program
add(X, Y, Z) :- Z is X + Y.
?- add(4, Y, X), write(X), write("\n").
output
Compiling the file:
c:\father
0 errors, 0 warnings.
Runtime Error at step 3:
The argument 2 of "+"
is "var" but has to be "str" or "int" or "float".
No.
program
add(X, Y, Z) :- Z is X + Y.
?- add(4, 5, 9), write(X), write("\n").
output
_9
Yes.
program
father(avraham, yitzchak).
father(yitzchak, yaakov).
ancestor(X, Y) :- father(X,Y).
ancestor(X, Y) :- father(X,Z), ancestor(Z, Y).
?- ancestor(avraham, X), write(X), write("\n").
output (selecting Run, then Next Answer)
Compiling the file:
C:\father
0 errors, 0 warnings.
yitzchak
Yes.
yaakov
Yes.
program
abs(X, Y) :- X = Y, X >= 0.
?- abs(4, T), write(T), nl.
output
4
Yes.
program
abs(X, Y) :- X = Y, X >= 0.
?- abs(-4, T), write(T), nl.
output
No.
program
abs(X, Y) :- Y = X, X >= 0.
abs(X, Y) :- Y = 0 - X.
?- abs(-4, T), write(T), nl.
output
4
Yes.
program:
append([], L, L).
append([H | T] , L2, [H | L3] ) :- append(T, L2, L3).
1) empty list + L = L
2) recursion step
appending a list [H | T] to any list L2 produces the list [H | L3], on condition that L3 is formed by appending T to L2.
try out an example.
Tuesday, March 07, 2006
More Prolog
Posted by joshwaxman at 7:56 AM
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment