% Facts about animals
animal(dog).
animal(cat).
animal(elephant).
animal(lion).
animal(tiger).
animal(snake).
animal(crocodile).
animal(bird).
animal(fish).
% Facts about characteristics
has_fur(dog).
has_fur(cat).
has_fur(lion).
has_stripes(tiger).
has_trunk(elephant).
has_scales(snake).
has_scales(crocodile).
can_fly(bird).
lives_in_water(fish).
% Rules for classification
mammal(X) :- animal(X), has_fur(X).
mammal(X) :- animal(X), has_stripes(X).
mammal(X) :- animal(X), has_trunk(X).
reptile(X) :- animal(X), has_scales(X).
bird(X) :- animal(X), can_fly(X).
fish(X) :- animal(X), lives_in_water(X).
% Classification predicate
classify(X) :- mammal(X), write(X), write(' is a mammal.'), nl.
classify(X) :- reptile(X), write(X), write(' is a reptile.'), nl.
classify(X) :- bird(X), write(X), write(' is a bird.'), nl.
classify(X) :- fish(X), write(X), write(' is a fish.'), nl.
classify(X) :- write(X), write(' is an unknown animal.'), nl.
% Initialization goal
:- initialization(main).
% Main goal
main :- classify(elephant),
classify(snake),
classify(fish),
classify(unicorn),
halt. Write, Run & Share Prolog code online using OneCompiler’s Prolog online compiler for free. It’s a simple and intuitive platform to experiment with logic programming in Prolog. OneCompiler supports standard Prolog syntax, great for learning, prototyping, and practicing logic-based problems.
Prolog (Programming in Logic) is a logic programming language associated with artificial intelligence and computational linguistics. It works through facts, rules, and queries, using a form of symbolic reasoning known as backward chaining. Prolog is declarative, meaning you describe what you want instead of how to compute it.
The following is a simple Prolog program that prints a greeting:
:- initialization(main).
main :-
write('Hello, World!').
Facts represent basic assertions about the world.
likes(alice, pizza).
likes(bob, pasta).
Rules define logical relationships using facts.
friends(X, Y) :- likes(X, Z), likes(Y, Z).
Queries are used to find information based on facts and rules.
?- likes(alice, What).
| Operator | Description |
|---|---|
:- | Rule definition |
, | Logical AND |
; | Logical OR |
= | Unification |
member(X, [X|_]).
member(X, [_|T]) :- member(X, T).
Prolog heavily relies on recursion.
factorial(0, 1).
factorial(N, F) :-
N > 0,
N1 is N - 1,
factorial(N1, F1),
F is N * F1.
This guide provides a quick reference to Prolog programming syntax and features. Start writing Prolog code using OneCompiler’s Prolog online compiler today!