PrologEZ
Foundations · Lesson 1 of 43

Hello, logic

Facts, queries, and what “false” really means.

Most languages tell the computer how to do something, step by step. Prolog works differently: you describe what is true, then ask questions. The engine figures out the steps.

A Prolog program is a collection of facts (and, later, rules). Below is a tiny knowledge base. Each line states one fact: alice likes pizza, bob likes sushi, and so on. Every fact ends with a full stop.

% facts: things we declare to be true
likes(alice, pizza).
likes(bob, sushi).
likes(carol, pizza).
likes(alice, tea).

Press Load to load the program. Then ask questions with queries, the prompt ?- means "is it true that…?". Queries run against every program cell above them.

?- likes(alice, pizza)
?- likes(bob, pizza)

Notice false. Prolog didn't prove that bob doesn't like pizza, it only failed to prove that he does. Anything not stated or derivable is treated as false. This is the closed-world assumption, and it runs through all of Prolog.

Asking with variables

Names starting with an uppercase letter are variables. A query with a variable asks: "for which values is this true?"

?- likes(alice, What)
?- likes(Who, pizza)
?- likes(Who, What)

When there are several answers, Prolog lists them in the order the facts appear. You can think of it as searching the program top to bottom.

Exercise: Teach Prolog two new facts

Extend the knowledge base so that bob likes tea and dave likes pizza. Then Check your work.