Reputation: 1025
I am trying to understand the following set of rules, which supposed to find the last element in a list (for instance my_list(X,[1,2,3])
gives X=3
).
my_last(X,[X]).
my_last(X, [_|L]) :- my_last(X, L).
I understand the first fact - X is the last element of a list if X is the only element in it, but how does the second rule work? this looks a bit strange to me as a prolog noob, I'd love to know if there's an intutive way to interprate it. T
Upvotes: 0
Views: 2840
Reputation: 58244
Read the Prolog predicate as logical rules. If there is more than one predicate clause for the predicate, you can think of it as "OR":
my_last(X,[X]).
X
is the last element of the list,[X]
.
my_last(X, [_|L]) :- my_last(X, L).
X
is the last element of the list[_|L]
ifX
is the last element of the listL
.
The second clause is a recursive definition. So it does, ultimately, need to terminate with the recursive call not matching the head of the recursive clause that is calling it. In this case, L
eventually becomes []
and will no longer match [_|L]
. This is important because, otherwise, you will get an infinite recursion.
Upvotes: 2