Prolog Recursion in lists, last but one element

前端 未结 6 676
闹比i
闹比i 2020-12-21 02:36

The question is to find the last but one character in a list, e.g.

?- last_but_one(X, [a,b,c,d]).
X = c.

My code is:

last         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-21 03:02

    another solution :

    • firstly, the list must be of length >= 2,
    • also the last length element of the list = 1

    code :

    last_but_one(R,[X|Rest]):-
       (  Rest=[_], R=X
       ;  last_but_one(R,Rest)
       ). 
    

    Test :

    | ?- last_but_one(Elem,List).
    List = [Elem,_A] ? ;
    List = [_A,Elem,_B] ? ;
    List = [_A,_B,Elem,_C] ? ;
    List = [_A,_B,_C,Elem,_D] ? ;
    List = [_A,_B,_C,_D,Elem,_E] ? ;
    List = [_A,_B,_C,_D,_E,Elem,_F] ? ;
    List = [_A,_B,_C,_D,_E,_F,Elem,_G] ? ;
    List = [_A,_B,_C,_D,_E,_F,_G,Elem,_H] ? 
    yes
    

    Hope this idea help you

提交回复
热议问题