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


i cannot understand why predicate not work expect.i thought tail of list list 1 item last element of list.so when run query last(x,[1,2,3]) result x=3 take false.

last(item,[_|[item]]).

what last try , unify second argument list 2 elements. list?

  • this empty list: []
  • this non-empty list: [_|rest]

here, rest must list. can empty list, or non-empty list. here proper lists of length 1, 2, 3: [1|[]], [1|[2|[]]], [1|[2|[3|[]]]]. important understand that:

?- [1] = [x|[]]. x = 1.  ?- [1,2] = [x|[y|[]]]. x = 1, y = 2.  ?- [1|[2]] = [x|[y|[]]]. x = 1, y = 2. 

you can @ this answer on programmers stackexchange different ways of defining last/2 in prolog.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -