Prolog Tutorial

Notes

The 3 basic ideas in prolog:

  • Facts: Assertions about the world (e.g., “Socrates is a man”).

  • Rules: Conditional statements (e.g., “If someone is a man, they are mortal”).

  • Queries: Questions you ask the system (e.g., “Is Socrates mortal?”).

Facts

parent(bob, alice).
parent(bob, bill).
parent(alice, charlie).

Rules

grandparent(X, Z) :-
    parent(X, Y),
    parent(Y, Z).

Queries

?- parent(bob, alice).

Output: true.

Ask a Variable question:

?- parent(bob, Who).

Output: Who = alice ; (Press ; to see the next result)

Output: Who = bill.

Syntax Rules

Feature

Syntax Example

Notes

Atoms

apple, socrates

Must be lowercase.

Variables

X, Person

Must be uppercase.

The “If”

:-

Separates the head from the body.

The “And”

,

Used to link conditions in a rule.

The “Or”

;

Used to provide alternatives.

The End

.

Every statement must end with a period.

Code

% --- The Identification Tool ---

% Start the program by typing 'go.' in the terminal.
go :- 
    hypothesize(Animal),
    write('I guess that the animal is: '),
    write(Animal), nl,
    undo.

% Hypotheses to be tested
hypothesize(cheetah) :- cheetah, !.
hypothesize(tiger)   :- tiger, !.
hypothesize(giraffe) :- giraffe, !.
hypothesize(zebra)   :- zebra, !.
hypothesize(ostrich) :- ostrich, !.
hypothesize(penguin) :- penguin, !.
hypothesize(unknown). % Default if no rules match

% --- Animal Rules ---
% These define what makes a specific animal.
cheetah :- mammal, carnivore, verify(has_tawny_color), verify(has_dark_spots).
tiger   :- mammal, carnivore, verify(has_tawny_color), verify(has_black_stripes).
giraffe :- ungulate, verify(has_long_neck), verify(has_long_legs).
zebra   :- ungulate, verify(has_black_stripes).
ostrich :- bird, verify(does_not_fly), verify(has_long_neck).
penguin :- bird, verify(does_not_fly), verify(swims), verify(is_black_and_white).

% --- Classification Rules ---
% These help categorize the animal further.
mammal    :- verify(has_hair), !.
mammal    :- verify(gives_milk).
bird      :- verify(has_feathers), !.
bird      :- verify(flys), verify(lays_eggs).
carnivore :- verify(eats_meat), !.
carnivore :- verify(has_pointed_teeth), verify(has_claws), verify(has_forward_eyes).
ungulate  :- mammal, verify(has_hooves), !.
ungulate  :- mammal, verify(chews_cud).

% --- The "Memory" and Question Engine ---
% This prevents Prolog from asking the same question twice.
:- dynamic yes/1, no/1.

verify(S) :-
    (yes(S) -> true ;
    (no(S)  -> fail ;
    ask(S))).

ask(Question) :-
    write('Does the animal have the following attribute: '),
    write(Question), write('? (y/n) '),
    read(Response), nl,
    ( (Response == yes ; Response == y)
      -> assert(yes(Question)) ;
         assert(no(Question)), fail).

% Clean up the memory after a run
undo :- retract(yes(_)), fail.
undo :- retract(no(_)), fail.
undo.