How to get the 2 last values from a list in recursion and in tail-recursion?

前端 未结 1 586
感动是毒
感动是毒 2021-01-28 03: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

相关标签:
1条回答
  • 2021-01-28 04:32

    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.

    0 讨论(0)
提交回复
热议问题