indexINTERACTIVE PROLOG GUIDE
© Roman Barták 1997


Table of Contents

Previous Chapter
(implementations)

Next Chapter
(examples)


INTRODUCTORY SAMPLES

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).
 
revert(List,RevList):-
rev(List,[],RevList).
 
rev([H|T],S,R):-
rev(T,[H|S],R).
rev([],R,R).
 

perm/2
permutation generator ([1,2,3]->[1,2,3];[2,1,3];[2,3,1],[1,3,2],[3,1,2],[3,2,1])
usage: ?-perm([1,2,3],P).
 
perm([H|T],Perm):-
perm(T,SP),insert(H,SP,Perm).
perm([],[]).
 
insert(X,T,[X|T]).
insert(X,[H|T],[H|NT]):-
insert(X,T,NT).


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).
 
turing(State,[Letter|Left]-Right,FinalTape):-
c(State,Letter,NewState,Write,Move),
move(Move,[Write|Left]-Right,NewTape),
turing(NewState,NewTape,FinalTape).
turing(State,Tape,Tape):-
f(State).
 
move(none,Tape,Tape).
move(left,[X|Left]-Right,NewLeft-NewRight):-
(Left=[] -> NewLeft=[free] ; NewLeft=Left),
(Right=[free] -> NewRight=[X] ; NewRight=[X|Right]).
move(right,Left-[X|Right],NewLeft-Right):-
Left=[free] -> NewLeft=[X] ; NewLeft=[X|Left].
move(right,Left-[],NewLeft-[]):-
Left=[free] -> NewLeft=Left ; NewLeft=[free|Left].


Table of Contents

Previous Chapter
(implementations)

Next Chapter
(examples)


Last update 6th October 1997
Designed and maintained by Roman Bartak
© October 1997