2011-10-07 53 views

回答

0

邏輯編程的第一步,從基礎案例開始。當少於三個元素時,你想要發生什麼?我想你想要一個空的列表?

without_last_three([], []). 
without_last_three([_], []). 
without_last_three([_,_], []). 
without_last_three([_,_,_], []). 

現在,超過三個元素的列表,你想保留的第一個元素,並刪除三位來自剩餘的元素。您可能會首先嚐試寫入:

without_last_three([A|L], [A|M]) :- without_last_three(L, M). !!wrong 

但這會由於回溯而導致不正確的結果。要解決這個問題最簡單的方法是驗證L具有以上三個要素:

without_last_three([A,B,C,D|L], [A|M]) :- without_last_three([B,C,D|L], M). 

但一個更優雅的解決方案是使用Prolog的剪輯操作:

without_last_three([A|L], [A|M]) :- !, without_last_three(L, M). 

要實現without_first_three,沒有得到無聊,你可以簡單地逆轉列表,刪除過去三年,並再次翻轉:

without_first_three(I, O) :- reverse(I, A), without_last_three(A, B), reverse(B, O). 

,或者你可以只寫了一些很簡單的規則:

without_first_three([], []). 
without_first_three([_], []). 
without_first_three([_,_], []). 
without_first_three([_,_,_|L], L). 

(思考一下,也許這會更好地在without_first_three方面實現without_last_three,而不是相反方向)!

3

你可能想嘗試這樣的:

without_last_three([_,_,_], []). 
without_last_three([Head|Tail], [Head|NTail]):- 
    without_last_three(Tail, NTail). 

without_three_sides([_,_,_|L], L2):- 
    without_last_three(L, L2). 

第一個謂詞將返回一個列表,而最後的三個要素,並在失敗的情況下還有不到三個要素。

第二個謂詞將返回一個沒有第一個和最後三個元素的列表,並且在少於六個元素的情況下失敗。

3

Prolog的是從其他語言有點不同,但它也有一個libray(ISO標準)是值得學習:

delete_last_3(L, L1) :- 
append(L1, [_,_,_], L). 

現在其他要求來容易:

delete_first_and_last_3(L, L2) :- 
    append([_,_,_], LT, L), delete_last_3(LT, L2). 

測試:

?- delete_last_3([1,2,3,4,5,6,7],X). 
X = [1, 2, 3, 4] . 

?- delete_first_and_last_3([1,2,3,4,5,6,7,8,9],L). 
L = [4, 5, 6] . 
+1

如果append/3被允許,我認爲OP不想使用,你可以重寫delete_first_and_last_3一個追加:'append([_,_,_ | L2],[_,_,_],L)'。 – gusbro

相關問題