Reading — step 1 of 5
Learn
~1 min readRecursion and Lists
Lists in Prolog are written [a, b, c]. The cons pattern [H | T] destructures into head H and tail T:
% A list of three elements
[1, 2, 3]
% Same list, written as cons
[1 | [2, 3]]
[1 | [2 | [3 | []]]]
Classic recursive predicates:
% length of a list
list_length([], 0).
list_length([_ | T], N) :-
list_length(T, N1),
N is N1 + 1.
% sum of a list of numbers
list_sum([], 0).
list_sum([H | T], S) :-
list_sum(T, S1),
S is H + S1.
% membership
member(X, [X | _]).
member(X, [_ | T]) :- member(X, T).
Built-in lists library predicates: length/2, append/3, reverse/2, member/2, sort/2, msort/2, nth0/3, nth1/3. Most Prologs include them.
List comprehensions don't exist; you build new lists via recursion or use findall/3 to collect query results.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…