All Prolog Programs

Note

All of these programs were used in the tutorial documentation. This page is a quick way to access the basic features of prolog for when they are needed.

Hello World

:- initialization(main).
main :- write('Hello World!').

Knowledge Base 1

girl(priya).
girl(tiyasha).
girl(jaya).
can_cook(priya).

Knowledge Base 2

sing_a_song(ananya). %fact
listens_to_music(rohit). %fact
listens_to_music(ananya) :- sing_a_song(ananya). %rule
happy(ananya) :- sing_a_song(ananya). %rule
happy(rohit) :- listens_to_music(rohit). %rule
playes_guitar(rohit) :- listens_to_music(rohit). %rule 

Knowledge Base 3

can_cook(priya).
can_cook(jaya).
can_cook(tiyasha).
likes(priya,jaya) :- can_cook(jaya).
likes(priya,tiyasha) :- can_cook(tiyasha).

Family Tree

female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):- parent(X,Y),male(X).
haschild(X):- parent(X,_).
sister(X,Y):- parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.

Loops

count_to_10(10) :- write(10),nl.count_to_10(X) :-   write(X),nl,   Y is X + 1,   count_to_10(Y).
count_down(L, H) :-   between(L, H, Y),   Z is H - Y,   write(Z), nl.
count_up(L, H) :-   between(L, H, Y),   Z is L + Y,   write(Z), nl.

Disjunction

   parent(jhon, bob).
   parent(lili, bob).
   male(jhon).
   female(lili).

   % Conjunction Logic
   father(X, Y) :- parent(X, Y), male(X).
   mother(X, Y) :- parent(X, Y), female(X).

   % Disjunction Logic
   child_of(X, Y) :- father(X, Y); mother(X, Y).

If Else

% If-Then-Else statement
   gt(X, Y) :- X >= Y, write('X is greater or equal').
   gt(X, Y) :- X < Y, write('X is smaller').

   % If-Elif-Else statement
   gte(X, Y) :- X > Y, write('X is greater').
   gte(X, Y) :- X =:= Y, write('X and Y are same').
   gte(X, Y) :- X < Y, write('X is smaller').