Memra

Prolog programming drills

◈ 6 cards

Write the exam Prolog from a blank page — product-of-list (Q3), factorial, and min-cost path — then verify the logic in Python.

Writing Prolog by hand on the exam

The exam lets you answer Q3 in Prolog (or Lisp). Assignments A1/A3 are pure Prolog: factorial, list indices, acyclic paths, min-cost paths. So this drill is about reproducing the shape of a recursive Prolog predicate cold: a base case plus a recursive step that decomposes a list as [H|T].

The recursion template

Every list predicate follows the same skeleton:

pred([], BaseValue).                 % base: empty list
pred([H|T], Result) :-               % recursive: split head/tail
    pred(T, Sub),                    % solve the tail
    combine(H, Sub, Result).         % fold the head back in

factorial (A3) is the integer analogue — base case 0, recursive step multiplies down:

fact(0, 1).
fact(N, F) :- N > 0, N1 is N - 1, fact(N1, F1), F is N * F1.

Worked example — Q3, product of a list

"Read a list and an integer ; test whether equals the product of ." The product is a fold with base value 1 (the multiplicative identity):

product([], 1).
product([H|T], P) :- product(T, PT), P is H * PT.

% query:  product([2,3,4], P), X =:= P.

Trace product([2,3,4], P): it recurses to product([], 1), then on the way back computes , , . So ; the test X =:= 24 is true for and false for .

Worked example — A1, minimum-cost path

With weighted edges edge(a,b,3), edge(b,c,1), edge(c,d,2), edge(b,d,5), collect every acyclic path's [Cost, Path] with findall/setof, then take the smallest. Sorting [Cost|_] lists puts the cheapest first:

min_path(S, G, Best) :-
    setof([C, P], path(S, G, P, C), [ [_,Best] | _ ]).

The cheapest route is at cost , beating the direct at .

We verify both logics in runnable Python below (our in-browser runtime is Python; the Prolog above is what you write on the exam).

call ↓[2,3,4][3,4][4][]return ↑241241Base 1; then 4·1=4, 3·4=12, 2·12=24.
Recursion runs left to right along the top row and the answers come back along the bottom. The base clause seeds the fold with 1, then each level multiplies its head back in: 4·1, 3·4, 2·12. Every list predicate you write on the exam has this same two-row shape.
NORMAL ~/memra/learn/comp-456/prolog-programming-drills utf-8 LF