Guide to Prolog Programming |
© Roman Barták, 1998 |
Home Prolog in Examples |
Previous | Contents | Next |
How does it work?
|
In this lesson I try to collect some features of Prolog language which I have found to be difficult to understand by students accustomed to procedural style of programming.
?-X is Y+2. % arithmetic expression cannot be evaluated because Y is free ?-H=5,T=[], L is [H|T]. % expression [H|T] is not arithmetic ?-X is 2, X is 3. % fails because it is impossible to change the value of X from 2 to 3
?-X=f(Y). % returns X/f(Y) ?-f(g(Y))=f(X). % returns X/g(Y) ?-X=1+2. % returns X/1+2 ?-3=1+2. % fails (3 is syntactically different from 1+2)
member(X,[X|T]). member(X,[_|T]):-member(X,T). ?-member(1,[1,2,3]). % usage as a test ?-member(X,[1,2,3]). % usage as a member generator (returns successively X=1, X=2, X=3) ?-member(1,L). % usage as a list generator (returns L=[1|_], L=[_,1|_], L=[_,_,1|_] etc.) ?-member(X,L). % generator of general lists containing X (returns L=[X|_], L=[_,X|_], L=[_,_,X|_] etc.)
?-member(Y,[[1,2],[3,4]]),member(X,Y). % returns X=1,X=2,X=3,X=4 successively ?-member(Y,[[1,2],[3,4]]),member(X,Y),!. % returns X=1 only ?-member(Y,[[1,2],[3,4]]),!,member(X,Y). % returns X=1, X=2 successively ?-!,member(Y,[[1,2],[3,4]]),member(X,Y). % returns X=1,X=2,X=3,X=4 successively
not P:-P,!,fail. not P.
p(a). p(b). q(c). ?-not p(X), q(X). % fails ?-q(X), not p(X). % succeeds with X=c
|
|
Designed and maintained by Roman Barták |
Previous | Contents | Next |