5. Terms and unification
So far, the arguments were simple names. In this chapter, you build structured data, and learn how Prolog matches it.
Terms
All data in Prolog is a term. There are four kinds.
| Kind | Examples |
|---|---|
| Atom | react, my_app, [], 'Hello, world' |
| Number | 42, -7, 3.14 |
| Variable | X, Package, _ |
| Compound term | version(18, 2, 0), point(X, 3) |
An atom that starts with an uppercase letter or has spaces must be in single quotes, such as 'React'.
A compound term has a name and arguments, like a fact. But it is data, not a statement. version(18, 2, 0) is just a value with three parts, like the object { major: 18, minor: 2, patch: 0 } in JavaScript. Prolog doesn't run it.
Compound terms can be nested.
The first query takes the parts of the version apart, right in the query. The second one gets the whole version(...) term in one variable.
Unification
Matching two terms is called unification. You can ask for it directly with =.
The rules are simple.
- Two atoms or numbers unify if they are the same.
- A variable unifies with anything, and gets that value.
- Two compound terms unify if they have the same name, the same number of arguments, and each pair of arguments unifies.
f(X, X) = f(a, b) fails, because X can't be a and b at the same time.
= is not assignment. It works in both directions, and once a variable has a value, it keeps it. There is no way to change the value of a variable. To get a different value, Prolog backtracks and forgets the old one.
Matching in the head
Every time Prolog uses a clause, it unifies the query with the head. So the head can take data apart, like destructuring in JavaScript.
Neither clause has a body. The head does all the work.
The head can also choose a clause by the shape of the data. Each clause handles one shape, like a switch on a tagged union in TypeScript.
Operators are terms too
1 + 2 looks like a calculation, but in Prolog it is just the compound term +(1, 2). The + is written between the arguments only to be easier to read.
1 + 2 = 3 is false, because the term +(1, 2) is not the number 3. write_canonical/1 prints a term without operators, so you can see that * is inside +. nl/0 starts a new line after it. Chapter 7 shows how to compute with these terms.
X-Y is another useful term. It is -(X, Y), and Prolog programs often use it for a pair of values, such as react-18 or a point 3-4.
Try it
- Write facts
file(Name, size(Bytes))for three files, and a query that finds the names and sizes. - Write
swap(X-Y, Y-X), a fact. Ask?- swap(1-2, P).and?- swap(P, a-b).