Reputation: 115
I cannot understand why this predicate do not work as i expect.I thought that tail of list would be a list with only one item which would be the last element of list.So when i run query last(X,[1,2,3]) the result would be X=3 but i take false.
last(Item,[_|[Item]]).
Upvotes: 0
Views: 904
Reputation:
What your last
does is to try and unify the second argument to a list with exactly two elements. So what is a list?
[]
[_|Rest]
Here, Rest
must be a list. So it can be the empty list, or a non-empty list. Here are proper lists of length 1, 2, 3: [1|[]]
, [1|[2|[]]]
, [1|[2|[3|[]]]]
. It is important to understand that:
?- [1] = [X|[]].
X = 1.
?- [1,2] = [X|[Y|[]]].
X = 1,
Y = 2.
?- [1|[2]] = [X|[Y|[]]].
X = 1,
Y = 2.
You can look at this answer on Programmers Stackexchange for different ways of defining last/2
in Prolog.
Upvotes: 1