簡體   English   中英

如何從Prolog列表中刪除最后n個元素?

[英]How can I remove the last n elements from a list in 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).
without_last_n(Old, N, New) :-
    length(Tail, N),
    append(New, Tail, Old).

測試運行:

?- 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]

更新。 要在N大於列表的長度時成功使用[] ,可以添加第二個子句:

without_last_n(Old, N, []) :-
    length(Old, L),
    N > L.

這是一個一般情況:

without_last_n(L, N, []) :-
    nonvar(L), nonvar(N),
    length(L, M),
    N > M.
without_last_n(L, N, R) :-
    without_last_n_(L, N, R).

without_last_n_(L, N, []) :-
    length(L, N).
without_last_n_([H|T], N, [H|T1]) :-
    without_last_n_(T, N, T1).

這滿足了給定的要求,並且可以用於各種變量實例化方案。 使解決方案稍微復雜一點的是沒有without_last_n(L, N, []). 如果N大於L的長度,則必須成功。 如果這不是without_last_n_/3 ,那么沒有問題的簡單得多而無需使用without_last_n_/3即可。

測試中...

| ?- without_last_n([1,2,3,4], 3, R).

R = [1] ? ;

no
| ?- without_last_n([1,2,3,4], N, R).

N = 4
R = [] ? ;

N = 3
R = [1] ? ;

N = 2
R = [1,2] ? ;

N = 1
R = [1,2,3] ? ;

N = 0
R = [1,2,3,4]

(1 ms) yes
| ?- without_last_n([1,2,3,4], N, [1,2]).

N = 2 ? ;

no
| ?- without_last_n(L, 3, [1,2]).

L = [1,2,_,_,_] ? ;

no
| ?- without_last_n(L, 2, R).

L = [_,_]
R = [] ? ;

L = [A,_,_]
R = [A] ? ;

L = [A,B,_,_]
R = [A,B] ? ;

L = [A,B,C,_,_]
R = [A,B,C] ?
...
| ?- without_last_n(L, N, [1,2]).

L = [1,2]
N = 0 ? ;

L = [1,2,_]
N = 1 ? ;

L = [1,2,_,_]
N = 2 ? ;
...
| ?- without_last_n(L, N, R).

L = []
N = 0
R = [] ? ;

L = [_]
N = 1
R = [] ? ;

L = [_,_]
N = 2
R = [] ? ;

L = [_,_,_]
N = 3
R = [] ? ;
...
| ?-

此處可能存在的缺陷是without_last_n([1,2,3,4], N, R). 也許可以無限生成N = 5, R = []N = 6, R = []等的解,但是事實並非如此。 留給讀者練習。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM