Part of INTERACTIVE PROLOG GUIDE | Prev | TOC | Next |
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 ?-1 is 3-2. % first argument of "is" is not free variable ?-X is 1+2, X is 2*X. % first argument of second "is" is not free ?-H=5,T=[], L is [H|T]. % expression [H|T] is not arithmetic
?-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 member generator (returns successively X=1, X=2, X=3) ?-member(1,L). % usage as list generator (returns L=[1|_], L=[_,1|_], L=[_,_,1|_] etc.) ?-member(X,L). % generator (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 succesively ?-!,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
Part of INTERACTIVE PROLOG GUIDE | Prev | TOC | Next |