Course contentsShow
← Computer Science
Lesson 2159 of 2,87248. Programming ParadigmsFree lesson

Queries and Unification

How Prolog answers queries through pattern matching and unification of terms with variables.

Queries and Unification

You'll learn how Prolog answers your questions by matching patterns and binding variables to make them true.

The Core Idea

In Prolog, you ask questions (queries) and the system tries to find answers by unifying your query with facts and rules in its database. Unification is a pattern-matching process that attempts to make two terms identical by binding variables to values.

Think of unification like solving a fill-in-the-blank puzzle. If you have the pattern parent(X, bob) and a fact parent(alice, bob), Prolog tries to match them by setting X = alice. If it succeeds, the query is satisfied.

How It Works

When you submit a query like parent(X, bob), Prolog:

  1. Searches its database for facts and rules that could match
  2. Attempts unification by comparing the query structure with each candidate
  3. Binds variables to concrete values that make the match work
  4. Backtracks to find alternative solutions if you ask for more

Variables (capitalized in Prolog) are placeholders that unification fills in. Constants and already-bound variables must match exactly. For example, parent(alice, Y) unifies with parent(alice, bob) by binding Y = bob, but parent(alice, bob) won't unify with parent(charlie, bob) because alice and charlie don't match.

Multiple Solutions

If multiple facts match your query, Prolog can find them all through backtracking—undoing variable bindings and trying the next possibility. This makes logic programming naturally exploratory.

Key Takeaway:
Unification is Prolog's core mechanism: it answers queries by pattern-matching terms and binding variables to values that satisfy the match, backtracking to explore all possible solutions.