Unification, Lists, and Pattern Matching

If you’re an object-oriented or procedural programmer used to languages like Java, Ruby, Swift, or C++, you’re going to have some fun. Lists in Prolog are processed differently than they are in the other languages that use arrays. The reason is that Prolog is declarative, so it needs to be able to express facts about lists rather than iterate over them.

In this section, we’re going to write rules that use pattern matching, and that’s going to use a Prolog concept called unification.

Unification

Loosely defined, unification seeks to make the left and right sides match, filling in the variables it can. Here’s a simple example:

 ?- List = [1, 2, 3].
 List = [1, 2, 3].

That result is not surprising. It works ...

Get Programmer Passport: Prolog now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.