PrologEZ
Foundations ยท Lesson 2 of 43

Terms: the building blocks

Atoms, numbers, variables and compound terms.

Everything in Prolog, data, facts, rules, even whole programs, is made of terms. There are four kinds:

  • Atoms: alice, pizza, 'Hello World', []. Lowercase-first names, or anything in single quotes.
  • Numbers: 42, -7, 3.14.
  • Variables: X, Name, _tmp. Uppercase-first or underscore-first.
  • Compound terms: a name (the functor) with arguments in parentheses: author(frank_herbert), point(3, 4).

Facts like likes(alice, pizza) are themselves compound terms with the functor likes and two arguments. The number of arguments is the arity, and a predicate is identified by name and arity: likes/2.

% book(Title, Author, Year)
book(dune, author(frank_herbert), 1965).
book(emma, author(jane_austen), 1815).
book(neuromancer, author(william_gibson), 1984).

Compound terms can nest. Ask for pieces by putting variables where you want answers:

?- book(dune, author(Who), Year)
?- book(Title, author(jane_austen), _)

The bare underscore _ is the anonymous variable: "something goes here, but I don't care what". Every _ is a fresh, independent variable.

Inspecting terms

Prolog can look at terms too. These type-checking predicates ask what kind of thing you have:

?- atom(pizza)
?- atom(42)
?- number(3.14), \+ number(pizza)
?- atom('Hello World')
?- compound(author(frank_herbert))
?- functor(book(dune, author(x), 1965), Name, Arity)
?- var(X)

Exercise: Model a family

Write parent/2 facts (parent(Parent, Child).) for this family:

  • tom is a parent of bob and of liz
  • bob is a parent of ann and of pat