What your last
does is to try and unify the second argument to a list with exactly two elements. So what is a list?
- This is the empty list:
[]
- This is a non-empty 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.