How to get the 2 last values from a list in recurs

2019-03-06 01:40发布

问题:

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 tail-recursion? thanks!

Here is a code with tail recursion, can I make it more efficient?

last2_2([_|[H1|[H2|T]]],Y,Z):-last2_2([H1|[H2|T]],Y,Z).

last2_2([H1,H2],H1,H2).

回答1:

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.



标签: list prolog