Say that I want to remove the last element of a list. I can do it with append/3
:
append(WithoutLastElement, [_], List)
However, this leaves behind a choicepoint! Try append(X, [_], [1, 2])
, for example.
I can write my own predicate (taken from here)
list_butlast([X|Xs], Ys) :-
list_butlast_prev(Xs, Ys, X).
list_butlast_prev([], [], _).
list_butlast_prev([X1|Xs], [X0|Ys], X0) :-
list_butlast_prev(Xs, Ys, X1).
But I wonder if there's a way to use a built-in, the append/3
solution has the advantage of taking about 2 seconds to read and understand what is happening. list_butlast_prev
requires a little more thought.
I'm using SWI-Prolog and would appreciate answers which work there, but I'm also curious if it's possible in other Prologs.