Languages‎ > ‎Prolog‎ > ‎

Short Programs

Last Element

Find the last element of a list.

Usage example:
?- my_last(X,[a,b,c,d]).
X = d

Implementation:
%base case, if list consist of only one element%
my_last(X, [X]) :- !.
%other cases, else remove the head of the list and try the tail%
my_last(X, [_|T]) :- my_last(X,T).

Second to Last Element

Find the last but one element of a list. Assume that the list provided contains two or more elements.

Usage example:
?- second_to_last(X,[a,b,c,d]).
X = c

Implementation:
%base case, list contains 2 elements%
%use built-in function "length"%
second_to_last(X, [X|T]) :- length(T, 1), !.
%other case, list contains 3 or more elements, try tail.%
second_to_last(X, [_|T]) :- second_to_last(X, T).

Kth to Last Element

Find the K'th element of a list. The first element in the list is number 1.

Usage example:
?- element_at(X,[a,b,c,d,e],3).
X = c

Implementation:
%base case, the element is at position 1, the head of the list%
element_at(X,[X|_],1) :- !.
%given a list and position K>1, this predicate will iterate past the first K-1 times in the list%
element_at(X, [H|T], K) :- N is K-1, element_at(X, T, N).