Memra

List processing: [H|T], member, append, and recursion over lists

Decompose a list with [H|T], read member/2 and append/3, and write a recursive list predicate — building straight to the exam Q3 product-of-a-list task.

Lists as head and tail

Prolog's central data structure is the list, and almost every list predicate is built from one idea: a non-empty list is a head (its first element) followed by a tail (the rest of the list). The notation [H | T] unifies H with the first element and T with the remaining list. The empty list is [], and it is almost always the base case of a list recursion.

?- [H | T] = [2, 3, 4].
H = 2, T = [3, 4].

The classic list predicates

member/2 — is X in the list? It is in the list if it is the head, *or* it is a member of the tail (an or-choice across two clauses):

member(X, [X | _]).
member(X, [_ | T]) :- member(X, T).

append/3append(A, B, C) holds when C is A followed by B. The recursion peels one element off A per step:

append([], B, B).
append([H | T], B, [H | R]) :- append(T, B, R).

The pattern is always the same: a base case on [], and a recursive step that handles the head and recurses on the tail.

Worked example — product of a list (exam Q3)

Exam Q3 reads a list Y and an integer X, then tests whether X equals the product of the elements of Y. The core is a recursive product predicate:

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

Read it: the product of the empty list is 1 (the multiplicative identity, the base case); the product of [H | T] is H times the product of the tail. Then the top-level check just compares:

check(Y, X) :- product(Y, P), X =:= P.

=:= is arithmetic equality. Tracing product([2,3,4], P) mirrors factorial: it descends to product([], 1), then multiplies back up — 1, then 4*1=4, then 3*4=12, then 2*12=24. So check([2,3,4], 24) succeeds and check([2,3,4], 10) fails.

The Python exercise implements the same head-times-product-of-tail recursion so the structure is muscle memory before you write the Prolog by hand.

NORMAL ~/memra/learn/comp-456/list-processing utf-8 LF