Previous Up Next

4.7  List processing

Lists are probably the most heavily used data structure in Prolog and ECLiPSe. Apart from unification/matching, the most commonly used list processing predicates are: append/3, length/2, member/2 and sort/2. The append/3 predicate can be used to append lists or to split lists:

?- append([1, 2], [3, 4], L).
L = [1, 2, 3, 4]
Yes (0.00s cpu)
?- append(A, [3, 4], [1, 2, 3, 4]).
A = [1, 2]
More (0.00s cpu)
No (0.01s cpu)
?- append([1, 2], B, [1, 2, 3, 4]).
B = [3, 4]
Yes (0.00s cpu)

The length/2 predicate can be used to compute the length of a list or to construct a list of a given length:

?- length([1, 2, 3, 4], N).
N = 4
Yes (0.00s cpu)
?- length(List, 4).
List = [_1693, _1695, _1697, _1699]
Yes (0.00s cpu)

The member/2 predicate can be used to check membership in a list (but memberchk/2 should be preferred for that purpose), or to backtrack over all list members:

?- memberchk(2, [1, 2, 3]).
Yes (0.00s cpu)
?- member(X, [1, 2, 3]).
X = 1
More (0.00s cpu)
X = 2
More (0.01s cpu)
X = 3
Yes (0.01s cpu)

The sort/2 predicate can sort any list and remove duplicates:

?- sort([5, 3, 4, 3, 2], Sorted).
Sorted = [2, 3, 4, 5]
Yes (0.00s cpu)
For more list processing utilities, see the documentation for library(lists).

Previous Up Next