2015-11-05 69 views
1

我不得不寫來濾除特定列表迴文(迴文是單詞哪都一樣像ABBA反向)功能Prolog的遞歸如預期

palindroom([], []). 
palindroom([X|Xs], Y):- 
    ( atom_chars(X, Z), 
     reverse(Z, K), 
     atom_chars(D,K), 
     atom_chars(P,Z), 
     D==P, 
     palindroom(Xs,[P|Y]) 
    ; 
     palindroom(Xs,Y) 
    ). 

我榜上無名ELEM成char不工作數組然後反轉並使其返回到一個字符串,然後兩者進行比較,如果是我添加它Y.

這裏是我的堆棧跟蹤的一切是正確下去,直到:

[trace] 44 ?- palindroom(["abba"], X). 
Call: (7) palindroom(["abba"], _G5269) ? creep 
Call: (8) atom_chars("abba", _G5351) ? creep 
Exit: (8) atom_chars("abba", [a, b, b, a]) ? creep 
Call: (8) lists:reverse([a, b, b, a], _G5363) ? creep 
Exit: (8) lists:reverse([a, b, b, a], [a, b, b, a]) ? creep 
Call: (8) atom_chars(_G5386, [a, b, b, a]) ? creep 
Exit: (8) atom_chars(abba, [a, b, b, a]) ? creep 
Call: (8) atom_chars(_G5386, [a, b, b, a]) ? creep 
Exit: (8) atom_chars(abba, [a, b, b, a]) ? creep 
Call: (8) abba==abba ? creep 
Exit: (8) abba==abba ? creep 
Call: (8) palindroom([], [abba|_G5269]) ? creep 
Fail: (8) palindroom([], [abba|_G5269]) ? creep 
Redo: (7) palindroom(["abba"], _G5269) ? creep what is happening here? and why? 
Call: (8) palindroom([], _G5269) ? creep 
Exit: (8) palindroom([], []) ? creep 
Exit: (7) palindroom(["abba"], []) ? creep 
X = []. 

我有另一個程序有同樣的問題,有人能幫助我嗎?是遞歸的基礎錯誤還是smt?

編輯! 得到它與

palindrome(Xs) :- 
    reverse(Xs, Xs). 

cycle([],[]). 
cycle([X|Xs], Y):- 
    atom_chars(X,Z), 
    palindrome(Z), 
    Y = [X|K], 
    cycle(Xs,K); 
    cycle(Xs,Y). 

工作,我在序言誤解遞歸畢竟。謝謝@repeat和@lurker

+0

@lurker我有字符串的列表,其中該程序檢查是否它的元素([「ABBA」,「比薩餅」,「番茄」] = [「ABBA」])是迴文並且僅返回迴文如結果 – DarkFeud

+0

好吧,對不起,我誤解了。你應該考慮擁有一個謂詞「迴文/ 1」,只有當它的論點是迴文時,它才能成功。然後有一個單獨的謂詞遍歷你的列表,並使用'palindrome/1'來檢查每個謂詞,如果成功,則將它包含在新列表中,或者使用'findall/3',條件是'(member(W,WordLilst ),迴文(W))'。 – lurker

回答

2

如何定義palindrome/1這樣,使用廣泛可用的列表謂詞reverse/2

palindrome(Xs) :- 
    reverse(Xs, Xs). 

示例查詢:

:- palindrome([a,b,b,a]). 
true. 

:- palindrome([a,b,X,Y]). 
X = b, Y = a. 

最後,讓我們不要忘記最普通的查詢!

?- palindrome(Xs). 
    Xs = [] 
; Xs = [_A] 
; Xs = [_A,_A] 
; Xs = [_A,_B,_A] 
; Xs = [_A,_B,_B,_A] 
; Xs = [_A,_B,_C,_B,_A] 
... 
+0

這可能工作,但你有任何提示爲什麼我不能像我想要的那樣返回列表Z.我真的很想知道我做錯了什麼? (拋開實現,也許我在做一些普遍錯誤的事情,在prolog中遞歸)@repeat – DarkFeud

+1

@DarkFeud在我的評論中看到您的原帖。你應該嘗試用遞歸的palindromes(List,Palindromes)謂詞,使用「迴文/ 1」謂詞重複在這裏顯示。 – lurker

+0

@lurker :) – DarkFeud