Prolog:删除最后一个列表元素

时间:2015-11-15 20:17:06

标签: list prolog

我成功反转了一个清单:

reverse([],Z,Z).
reverse([H|T],Z,A) :- reverse(T,Z,[H|A]).

我想要一个删除列表最后一个元素的程序。

1 个答案:

答案 0 :(得分:0)

为什么你需要改变任何东西?

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% remove_last(IN_LIST, OUT_LIST).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% 1. No last element to remove, fail - cut stops alternatives
remove_last([], []) :- !, fail.

% 2. Only one element in list - return empty list - cut stops alternatives
remove_last([_], []) :- !.

% 3. If the rules above did not match, preserve the head of the
% list in the result list and recurse...
remove_last([X | T], [X | T2]) :-
    remove_last(T, T2).