如何从Prolog中的列表中删除最后n个元素?

ser*_*gur 1 list prolog

我想删除Prolog中列表的最后n个元素,并将其放在另一个列表中,如L2.如果我知道要删除的元素的确切数量说3,这里是代码.但我坚持变量n案例.顺便说一下,如果列表的长度小于n,我想返回一个空字符串.谢谢.

without_last_three([], []).
without_last_three([_], []).
without_last_three([_,_], []).
without_last_three([_,_,_], []).
without_last_three([Head|Tail], [Head|NTail]):-
   without_last_three(Tail, NTail).
Run Code Online (Sandbox Code Playgroud)

Ser*_*nko 5

without_last_n(Old, N, New) :-
    length(Tail, N),
    append(New, Tail, Old).
Run Code Online (Sandbox Code Playgroud)

测试运行:

?- without_last_n([a, b, c, d, e, f], 4, New).
New = [a, b] 

?- without_last_n([a, b, c, d, e, f], 777, New).
false.

?- without_last_n([a, b, c, d, e, f], 0, New).
New = [a, b, c, d, e, f]
Run Code Online (Sandbox Code Playgroud)

更新.[]在N大于列表长度时成功,可以添加第二个子句:

without_last_n(Old, N, []) :-
    length(Old, L),
    N > L.
Run Code Online (Sandbox Code Playgroud)