I try to collect some introductory PROLOG programs that can help you to understand underlying principles of PROLOG programming. Send me other examples or ideas of short programs to publish them in this page. Currently, I am working on a new subsite Learning Prolog via Examples which will contain much more examples of PROLOG code. As soon as this subsite infills by more examples I expect to remove this page. Tip: Use Copy&Paste function of the browser to move the code into the PROLOG environment.
member/2 test membership relation (member(3,[1,2,3])->true) also generates members of given list usage: ?-member(X,[1,2,3]).
member(X,[X|T]). member(X,[_|T]):-
member(X,T).
append/3 appends two lists ([1,2,3],[4,5]->[1,2,3,4,5]) usage: ?-append([1,2,3],[4,5],X). try also ?-append(A,B,[1,2,3,4,5]).
append([H|T],L2,[H|R]):-
append(T,L2,R2). append([],R,R).
revert/2 list reversion ([1,2,3]->[3,2,1]) usage: ?-revert([1,2,3],R).
solve/1 PROLOG interpreter written in PROLOG (so-called vanilla meta-interpreter) usage: ?-solve(PrologGoal).
solve(true). solve((A,B)):-
solve(A), solve(B). solve(A):-
clause(A,B), solve(B).
turing/3 emulator of Turing machine (more information can be found here-only in Czech) usage: ?-turing(InitialState,LeftPartOfTape-RightPartOfTape,ResultTape).