Prolog Lecture Notes: Unification, Lists, Control Flow, and Family Tree (Vocabulary)
Unification
- Constant Unification: ?- apple = apple. Prolog treats constants as equal only to themselves; constant apple unifies with itself, yielding true. Represented as .
- Variable Binding: ?- X = 42. The variable X is instantiated/bound to the constant 42; result: .
- Variable Unification: ?- Y = apple. A variable can unify with a constant; result: .
- Structural Unification: ?- color(red, Color) = color(red, crimson). Same predicate with same arity; unification binds the variable Color to crimson; result: Color = crimson; overall result is true if other arguments align. color(red, Color) = color(red, crimson)
ightarrow Color = crimson. - Failure in Unification: ?- red = blue. Mismatched constants cause the unification to fail (false).
- Variable Identification: Example of how Prolog parses a clause and treats variables as placeholders. In
parent(X, Y) :- mother(X, Y); father(X, Y).
X and Y are variables identified by the parser and can be bound later during execution. - Practical note: Unification is the core operation that drives Prolog’s pattern matching and rule application.
Unification in Practice (Examples)
- Example program:
likes(sue, fondue).
likes(bob, fondue).
friends(X, Y) :- likes(X, Something), likes(Y, Something). - Query: ?- friends(sue, Y).
- From the rule, X unifies with sue and Something with fondue; the derived goal becomes:
friends(sue, Y) :- likes(sue, fondue), likes(Y, fondue). - Solving likes(Y, fondue) yields Y = sue; Y = bob.
- Final answers: Y = sue ; Y = bob.
- From the rule, X unifies with sue and Something with fondue; the derived goal becomes:
Execution Order
- Prolog uses a resolution-sequence search automatically to find a solution for a given goal.
- Forward Chaining (Derive from axioms/facts in the KB):
- Derives the goal from the facts and rules in the knowledge base.
- Efficient when there are many rules and relatively few facts.
- Backward Chaining (Start with the goal and resolve backwards):
- Generally more efficient and is the primary execution mechanism in Prolog programs.
- Particularly effective when rules are structured to decompose goals into subgoals.
- When rules are complex with many conditions, backward chaining is often more effective.
- Some problems suit forward chaining, others backward chaining; choice depends on knowledge base and goal structure.
Backward Chaining in Prolog
- Backward chaining follows a classic depth-first backtracking approach.
- Example goal: Snowy(C).
- Prolog tries to satisfy Snowy(C) by recursively applying rules and facts that can derive Snowy(C).
Depth-First Backtracking
- Prolog explores the search space in a depth-first manner.
- If it hits a dead end, it backtracks to the most recent choice point and tries alternatives.
- The order of rules and facts matters: Prolog uses the first matching rule/fact definition, then proceeds to the next if needed.
- Different orderings can lead to different solutions or non-terminating resolutions.
- Example around ancestor/2:
ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).
parent(john, mary).
parent(john, bob).
parent(mary, alice).
parent(bob, carol). - Query: ?- ancestor(X, carol).
- One ordering yields X = john; X = bob.
- If the rule order is swapped, results may differ (X = bob; X = john).
- Note: Changing rule order can cause non-terminating resolutions in some definitions (infinite recursion) if termination is not ensured.
- Visual gist: the search tree is traversed depth-first; wrong/bad orderings can cause infinite branches.
Prolog is Not Purely Declarative
- The order of facts and rules affects behavior; there is a left-to-right pursuit of sub-goals as part of backtracking.
- This makes Prolog partially imperative in style, since control flow depends on clause order and goal resolution order.
- Rearranging clauses can change outcomes or performance.
- Incorrect ordering or recursive rules without proper termination can cause infinite loops.
- Clause ordering also impacts search efficiency; thoughtful KB design is essential.
Arithmetic in Prolog
- Prolog supports arithmetic via the is operator, used to evaluate expressions and instantiate variables.
- Pattern: X is Expression; X becomes the value of Expression.
- Examples:
- X = 10 + 5
ightarrow X = 15 - X = 10 - 5
ightarrow X = 5 - X = 10 * 5
ightarrow X = 50 - X = 10 / 5
ightarrow X = 2 - X = 10 + 5 * 6 / 3
ightarrow X = 20 - is(X, 1+2)
ightarrow X = 3 - A = 2, B = 3, X = 2+3 (unevaluated)
- A = 2, B = 3, X is A + B
ightarrow X = 5
- X = 10 + 5
- Error scenario: X is Y fails if variables are not sufficiently instantiated yet.
- Relational arithmetic operators: =:=, =,
- Important note: =:= and == compare numeric values after evaluation; == and = compare terms for structural equality/inequality (unification-based).
- Practical example: compare numbers after evaluation to decide control flow or branching.
Factorial Example
- Classic recursive definition:
fact(0, 1).
fact(A, B) :- A > 0, C is A - 1, fact(C, D), B is A * D. - Query: ?- fact(3, X).
- X = 6
- Process walk-through (summary):
- Unify A with 3; B will be computed; A > 0 succeeds; C = 2; recursive call fact(2, D); …
- Base case fact(0, F) yields F = 1; unwind to compute products: 3 * 2 * 1 = 6.
- A demonstration of backtracking: ?- fact(5, 2). false.
- The steps show expansion, recursion, and backtracking to reach a solution or failure.
Lists in Prolog
- Lists are fundamental: written in square brackets; empty list is []
- List construction: [Head | Tail] where Head is first element, Tail is remainder
- Examples:
- List = [1, 2, 3, 4, 5], First = 1, Rest = [2, 3, 4, 5]
- Nested list: [a, [b, c], d]
- Built list-destructuring: ?- List = [1,2,3,4,5], [First|Rest] = List.
User-defined first/2 predicate (destructuring lists)
- Options:
- first(X, List) :- List = [X | Xs].
- first(X, [X | Xs]).
- first(X, [X | _]).
- Examples: extract head of list, with various inputs, showing success/failure depending on input.
Tail and Second predicates (list decomposition)
- tail/2: tail([X|Y], Y).
- second/2: second([_, Second | _], Second).
- Examples show extracting tail and second element, including nested lists.
nth0/3 and nth1/3 for indexing
- nth0(N, Lst, X): 0-based index
- nth1(N, Lst, X): 1-based index
- Examples:
- nth0(3, [1,2,3,4,5], X) -> X = 4
- nth1(3, [1,2,3,4,5], X) -> X = 3
Accessing Elements and List Operations
- elementatn(N, List, Element) :- nth0(N, List, Element).
- extractevens([], []). extractevens([H|T], [H|Result]) :- 0 is H mod 2, extractevens(T, Result). extractevens([|T], Result) :- extractevens(T, Result).
- Examples: elementatn(2,[1,2,3,4,5],X) -> X = 3; elementatn(0,[1,2,3,4,5],X) -> X = 1; extract_evens([1,2,3,4,5,6], X) -> X = [2,4,6].
List Manipulation Predicates
- length/2: length of a list; can be defined recursively as well.
listlength([], 0). listlength([H|T], N) :- list_length(T, N1), N is N1 + 1. - member/2: checks membership; can be defined as recursion.
ismember(X, [X|T]). ismember(X, [H|T]) :- is_member(X, T). - append/3: concatenates two lists; can be user-defined:
listappend([], L, L). listappend([H|T], L, [H|L2]) :- list_append(T, L, L2). - Examples show concatenation, nesting effects with sublists.
List Predicates Examples
- sumlist([], 0). sumlist([Head|Tail], Sum) :- sum_list(Tail, RestSum), Sum is Head + RestSum.
- sorted([]).
sorted([_]).
sorted([A, B | T]) :- A =< B, sorted([B | T]). - lastelement(X, [X]). lastelement(X, [|L]) :- lastelement(X, L).
- range(From, To, L) produces all integers From..To.
range(I, I, [I]).
range(I, K, [I|L]) :- I < K, I1 is I + 1, range(I1, K, L). - Examples show lastelement and range results: lastelement(X,[a,b,c,d,e]) -> X = e; range(5,8,L) -> L = [5,6,7,8].
- duplicate(List, D) duplicates each element: duplicate([a,b,b,c], X) -> X = [a,a,b,b,b,b,c,c].
- splitlist(X, List, Less, GreaterEqual) partitions List into elements < X and >= X.
Example: splitlist(8,[3,10,5,2,19,15,20,7,8,11,5],Less,GreaterEqual)
- Less = [3,5,2,7,5]
- GreaterEqual = [10,19,15,20,8,11]
Control the Control Flow? The Cut Operator: !
- The cut (!) prunes backtracking to reduce search space.
- Example: ismember with cut to commit to the first successful clause: ismember(X, [X | ]):- !. ismember(X, [|T]):- ismember(X, T).
- The cut is powerful but must be used carefully to avoid removing valid alternative solutions.
- Factorial example with cut:
fact(N,1) :- N = 0, !.
fact(N,F) :- N > 0, M is N - 1, fact(M,F1), F is N * F1. - If N = 0, the first clause succeeds and cut prevents evaluating the second clause; without the cut, the second clause would end up failing in some cases. In practice, the cut can be used to optimize or emulate if-then-else behavior.
- Another example: min/3 with and without cut shows how cut affects the determinism of the predicate.
If-Then-Else Construct via Cut
- The cut can mimic if-then-else:
statement :- condition, !, thenpart. statement :- elsepart. - Example: compare_numbers(X, Y) with sequencing and cuts to produce one of three messages depending on comparison:
- compare_numbers(7,7). => "Numbers are equal."
- compare_numbers(7,11). => "Second number is greater."
- compare_numbers(11,7). => "First number is greater."
Negation Operator: '+'
- Negation as failure: w(X) :- q(X), + r(X).
- Notation: + represents logical negation (not).
- Examples:
- even_number(X) :- 0 is X mod 2.
- oddnumber(X) :- + evennumber(X).
- Queries: ?- oddnumber(7). -> true; ?- oddnumber(8). -> false.
- Other examples: ?- w(a). false. ?- w(e). true. ?- q(c). false. ?- w(c). false.
- Practical hotel-room example: hotelFull :- + vacantRoom(X). vacantRoom(13). vacantRoom(113).
?- hotelFull. false. - Important note: Prolog assumes lack of fact means false; negation relies on failure to prove the goal, not on proving its negation. When facts are incomplete, negation can be incomplete.
- Addressing incompleteness: home(X) :- person(X), + out(X).
- Query: ?- home(X). returns some individuals for whom there is no evidence they are out; may yield multiple results and even fail depending on knowledge base.
Family Tree: A Progressive KB (Prolog KB Construction)
The family tree KB evolves from simple parent facts to rich relational queries.
Basic facts (Example - Family Tree 1):
- parent(pam, bob). parent(tom, bob). parent(tom, liz). parent(bob, ann). parent(bob, pat). parent(pat, jim).
- Basic individuals: pam, tom, bob, liz, ann, pat, jim.
Simple queries (Family Tree 2-3):
- ?- parent(bob, pat). true.
- ?- parent(liz, pat). false.
- ?- parent(X, jim). X = pat.
- ?- parent(X, bob). X = pam ; X = tom.
- Other queries like ?- parent(X, tom). false. ?- parent(bob, X). X = ann ; X = pat.
Family Tree 3: full listing of parent pairs; demonstrates order of generated solutions when querying parent/2.
Family Tree 4-5: introduce grandparent via grandparent(X, Z) :- parent(X, Y), parent(Y, Z).
- Query examples: ?- grandparent(X, jim). X = bob.
- Determine tom’s grandchildren via grandparent(tom, X).
Family Tree 6-7: introduce offspring relation and gender facts.
- offspring(Y, X) :- parent(X, Y).
- maternal/paternal relations: mother(X, Y) :- parent(X, Y), female(X).
- female/male facts added for Pam, Liz, Ann, Pat, Tom, Bob, Jim.
- Initially, sister(X, Y) defined as sibling relation without gender and later refined to correct logic.
Family Tree 8-9: refine sister relation to include symmetry and non-reflexivity (X rac{=}{=}) to avoid trivial cases.
- Corrected sister rule: sister(X, Y) :- parent(Z, X), parent(Z, Y), female(X), X q Y.
Family Tree 10-11: add hasachild/1 using setof/3 to accumulate a unique set of parents; then hasachild(X) checks membership in set.
- hasachild(X) :- setof(Parent, Child^(parent(Parent, Child)), Parents), member(X, Parents).
- setof/3: setof(Variable, Goal, Set) collects all solutions to Goal, with Variable bound, sorts and removes duplicates.
- Example outcomes: hasachild(X) yields X = bob ; X = pam ; X = pat ; X = tom.
Family Tree 11-12: create a predecessor relation to capture transitive ancestry: predecessor(X, Z) :- parent(X, Z). predecessor(X, Z) :- parent(X, Y), predecessor(Y, Z).
- Examples: predecessor(pam, bob). true. predecessor(tom, jim). true. predecessor(pat, pam). false.
Family Tree 12-13: query examples for predecessor across the KB; demonstrates multiple chain possibilities and ordering.
Practical takeaways from Family Tree KB:
- How to build complex relations from simple facts.
- How to progressively add predicates (offspring, mother, sister, hasachild, setof, predecessor).
- How to query for parents, ancestors, siblings, and grandparents.
- How to handle duplicates and completeness with setof and explicit rules.
- Gender annotations enable more precise definitions (mother, sister).
- The order of facts and rules influences the answers and performance.
Connections to foundational principles:
- Unification is the engine powering rule matching and variable binding across all KB expansions.
- Recursion is used to define transitive relations (ancestor, predecessor, grandparent, etc.).
- Backtracking and cut (when used) control search space and termination behavior.
- Lists and list predicates illustrate data structure manipulation within logic programming.
Real-world relevance and implications:
- Prolog-style KBs map well to knowledge representation tasks (family trees, simple AI reasoning, rule-based systems).
- The need to design efficient rule ordering and to use features like setof to avoid duplicates and to manage query results.
Summary of key concepts to study:
- Unification basics: constants, variables, structural, and failure cases.
- Execution order: forward vs backward chaining, depth-first search, and backtracking.
- The cut operator and its use for control flow and termination guarantees.
- Negation as failure and the semantics of + in Prolog.
- Arithmetic: is, evaluation order, and numeric comparisons (:=, =
- List operations: head/tail, nth0/nth1, elementatn, extractevens, length, member, append, and various listPredicates examples (sumlist, sorted, lastelement, range, duplicate, splitlist).
- Complex KB design: parent, offspring, ancestor, grandparent, mother, sister, hasachild, setof, predecessor, and how to extend with gender info.