Prolog
Prolog is a logic programming language especially useful for artificial intelligence related purposes. Even though it is rather old (more than 40 years old) it is still used today.
A Prolog program is made of declarative statements named clauses, and is run by executing a query.
Clauses
There are two types of clause: facts and rules.
Facts
A fact is a statement which is always true. For example, "Yumemi is a company" is a fact. In Prolog, this could be written like this:
isCompany(yumemi).
In this clause, yumemi
is called an atom and can be thought of as a constant.
Rules
A rule contains a head and a body. It is used to infer new facts from existing ones. Here is an example:
hasWheels(X) :- car(X).
Here X
is a variable. It can be replaced by any atom as long as it's the same on both sides. This rule reads "X has wheels if X is a car".
Queries
A query is simply a question asked to the system, using the same syntax as for the clauses. Let's take a simple prolog program:
has(link, sword).
isWeapon(sword).
hasWeapon(A) :- has(A, B), isWeapon(B).
Live example
One can ask : "Does Link have a weapon ?" like this:
hasWeapon(link).
The output will be:
yes
One can also ask:
hasWeapon(X).
which means, "Who has a weapon ?" and get the following result:
X = link
yes
How does it work ?
When getting the query
hasWeapon(link).
the system looks for a rule which gives such a result. The first one which matches is
hasWeapon(A) :- has(A, B), isWeapon(B).
with A
= link
.
For hasWeapon(link)
to be true, has(link, B)
and isWeapon(B)
need to be true.
First, the engine tries to validate has(link, B)
, which is true for the fact
has(link, sword).
so B
becomes sword
.
Then, isWeapon(sword)
is true because the program contains exactly this fact.
Conclusion: has(link, B)
and isWeapon(B)
are true, so hasWeapon(link)
is true.