I need a predicate last_two(LST,Y,Z)
that assigns the last value of a list to Z
and the second-to-last to Y.
How can I do it in recursion? and how can I do it in
You could simplify the recursive case:
last2_2([_|T],X,Y) :- last2_2(T,X,Y).
This would make each recursive case faster (less pattern-matching), but causes it to go too far, and have to backtrack to get the last 2 elements. This would probably be of more benefit as the list gets longer (as the amount of backtracking is independent of the length of the list).
You could take this a step further, replacing the recursive case with:
last2_2([_,_|T],Y,Z):-last2_2(T,Y,Z).
last2_2([_,A,B],A,B).
Here, the recursive case strips off 2 elements at a time (at the cost of some more pattern-matching), and we need a second base case to handle odd-length lists.