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
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,_].