Skip to content

2. Syntax

1. Hello World

To write and run a “Hello, World!” program in Prolog on Ubuntu, follow these steps:

  1. Install SWI-Prolog (if not already installed): Open a terminal and run:

    Terminal window
    sudo apt-get update
    sudo apt-get install swi-prolog
  2. Create a Prolog file: Create a file called hello_world.pl using your favorite text editor:

    Terminal window
    nano hello_world.pl
  3. Write the Prolog code: Add the following code to the file:

    hello_world :- write('Hello, World!'), nl.

    Save and exit the editor (CTRL + X, then Y to confirm).

  4. Run the Prolog file: Open a terminal and run SWI-Prolog with your Prolog file:

    Terminal window
    swipl hello_world.pl
  5. Execute the hello_world predicate: Once inside the Prolog prompt, run the following:

    ?- hello_world.

    You should see:

    Hello, World!
    true.

2. Basics

The basics of Prolog revolve around logic programming, where you define relationships and rules, and Prolog uses them to derive conclusions. Here are the key concepts:

2.1 Facts

  • Facts state things that are unconditionally true.
  • Syntax: fact_name(arguments).
  • Example:
    parent(john, mary).
    This declares that John is a parent of Mary.

2.2 Rules

  • Rules define conditions under which something is true. They have a head (what you want to prove) and a body (conditions to be satisfied).
  • Syntax: head :- body.
  • Example:
    grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
    This means “X is the grandparent of Y if X is the parent of Z, and Z is the parent of Y.”

2.3 Queries

  • Queries are questions asked to Prolog to determine if certain facts or rules hold.
  • Syntax: ?- query.
  • Example:
    ?- parent(john, mary).
    This checks if John is a parent of Mary. Prolog will respond with true or false.

2.4 Variables

  • Variables in Prolog start with an uppercase letter and can take any value during computation.
  • Example:
    ?- parent(X, mary).
    This query asks, “Who is Mary’s parent?” and Prolog will return the possible values of X that satisfy the query.

2.5 Unification

  • Unification is the process of matching terms. In Prolog, terms unify if they are the same or if variables can be instantiated to make them the same.
  • Example:
    ?- parent(john, Y).
    Prolog tries to unify parent(john, Y) with the facts and returns the value of Y that makes the fact true (e.g., Y = mary).

2.6 Backtracking

  • Prolog uses backtracking to find all possible solutions to a query. If it finds a failure in satisfying a goal, it backtracks to the previous choice point and tries another path.
  • Example:
    ?- parent(john, X).
    If there are multiple children of John, Prolog will return one solution, and by typing ; after the first answer, Prolog will continue backtracking to find other solutions.

2.7 Lists

  • Lists are an important data structure in Prolog, denoted by square brackets [].
  • Example:
    ?- member(X, [1, 2, 3]).
    This query checks if X is a member of the list [1, 2, 3] and will return values like X = 1, X = 2, and so on.

2.8 Recursion

  • Prolog heavily relies on recursion to process structures like lists or to perform repeated operations.
  • Example:
    length([], 0).
    length([_|T], N) :- length(T, N1), N is N1 + 1.
    This defines the length of a list: if it’s empty, the length is 0; otherwise, it’s 1 plus the length of the tail.

2.9 Negation

  • Prolog uses negation as failure (\+), which means it assumes something is false if it cannot prove it to be true.
  • Example:
    ?- \+ parent(john, bob).
    This checks if John is not the parent of Bob.

2.10 The Cut Operator (!)

  • The cut (!) is used to control Prolog’s backtracking behavior, preventing Prolog from reconsidering alternative solutions once a decision is made.
  • Example:
    max(X, Y, X) :- X >= Y, !.
    max(_, Y, Y).
    This ensures that if X is greater than or equal to Y, the cut prevents further evaluation of the second clause.

2. Control Structures in Prolog

Prolog’s control structures determine how the program flow proceeds, including logical flow, recursion, and decision-making. Some of the most important control structures are:

  1. Conjunction (,)

    • The comma (,) is used to join conditions that must all be true for a rule to be satisfied.
    • Example:
      grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
      Here, both parent(X, Z) and parent(Z, Y) must be true for grandparent(X, Y) to be true.
  2. Disjunction (;)

    • The semicolon (;) represents logical OR. If one of the conditions is true, the whole statement is true.
    • Example:
      sibling(X, Y) :- parent(Z, X), parent(Z, Y).
      sibling(X, Y) :- step_sibling(X, Y).
      This says X and Y are siblings if they share a parent or if they are step-siblings.
  3. Negation (\+)

    • Prolog uses negation as failure (\+), meaning that if Prolog fails to prove a statement true, it assumes it to be false.
    • Example:
      not_parent(X, Y) :- \+ parent(X, Y).
      This states that X is not the parent of Y if it cannot be proven that X is a parent of Y.
  4. If-Then (->)

    • The -> operator allows for conditional execution. If the condition on the left is true, the right side will be executed.
    • Example:
      max(X, Y, Z) :- X > Y -> Z = X ; Z = Y.
      If X > Y is true, Z = X; otherwise, Z = Y.
  5. Cut (!)

    • The cut operator (!) is used to stop Prolog from backtracking beyond a certain point, committing to the current choice and pruning other alternatives.
    • Example:
      max(X, Y, X) :- X >= Y, !.
      max(_, Y, Y).
      Here, after confirming X >= Y, Prolog will not consider the second clause.
  6. Fail (fail)

    • The fail predicate always fails when executed, forcing backtracking.
    • Example:
      find_any(X) :- parent(X, _), write(X), fail.
      find_any(_).
      This will write all parents by forcing backtracking after each result.
  7. Recursion

    • Prolog programs often use recursion to iterate through data structures like lists.
    • Example:
      length([], 0).
      length([_|T], N) :- length(T, N1), N is N1 + 1.

3. Data Structures in Prolog

Prolog supports several types of data structures to represent different forms of knowledge:

  1. Atoms

    • Atoms are constants that represent simple entities. They can be any sequence of alphanumeric characters starting with a lowercase letter.
    • Example: john, mary, dog.
  2. Numbers

    • Prolog supports both integers and floating-point numbers.
    • Example: 3, 42.0.
  3. Variables

    • Variables are placeholders for values that will be determined during execution. Variables start with an uppercase letter.
    • Example: X, Person.
  4. Lists

    • Lists are the primary data structure in Prolog for storing collections of items. Lists are written with square brackets and can contain any terms, including other lists.
    • Example:
      [1, 2, 3]
      [apple, orange, banana]
      [X, Y, Z]
      Lists are recursive, where the head (first element) and tail (remaining list) are often processed separately.
      [Head | Tail].
  5. Tuples (Compound Terms)

    • Tuples are compound structures where multiple arguments are grouped under a functor.
    • Example:
      point(3, 4)
      date(2023, 09, 18)
      These are structures consisting of a functor (point or date) and the arguments (3, 4 or 2023, 09, 18).
  6. Strings

    • Prolog handles strings as a list of ASCII character codes. Alternatively, modern implementations allow string literals using double quotes (" ") as a shortcut.
    • Example: "Hello", "world".
  7. Functors

    • A functor is the name of a compound term. It represents a function or relation, but in Prolog, it’s more of a structural building block.
    • Example: person(john, 30), where person is the functor.
  8. Facts, Rules, and Queries

    • Facts: A basic data structure that defines relationships between entities.
      parent(john, mary).
    • Rules: A structure that defines a relationship based on conditions.
      sibling(X, Y) :- parent(Z, X), parent(Z, Y).
    • Queries: Structure used to ask questions of the Prolog system.
      ?- parent(john, mary).