Prolog Recursion in lists, last but one element

前端 未结 6 664
闹比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条回答
  •  攒了一身酷
    2020-12-21 03:11

    Here is another approach using DCGs. I think that this solution is much more "graphical", but it seems quite slow in SICStus:

    last_but_one_dcg(L, Ls) :-
       phrase( ( ..., [L,_] ), Ls).
    
    ... --> [].
    ... --> [_], ... .
    

    So we describe how a list must look like such that it has a last-but-one element. It looks like this: Anything (...) in front, and then two elements at the end.

    It gets a bit faster by expanding phrase/2. Note that the expansion itself is no longer a conforming program.

    last_but_one_dcgx(L, Ls) :-
       ...(Ls, Ls2),
       Ls2 = [L,_].
    

提交回复
热议问题