seinta
seinta

Reputation: 115

Predicate that take a list and give me the last item of this list do not work as i expect

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

Answers (1)

user1812457
user1812457

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?

  • 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.

Upvotes: 1

Related Questions