我不得不寫來濾除特定列表迴文(迴文是單詞哪都一樣像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
@lurker我有字符串的列表,其中該程序檢查是否它的元素([「ABBA」,「比薩餅」,「番茄」] = [「ABBA」])是迴文並且僅返回迴文如結果 – DarkFeud
好吧,對不起,我誤解了。你應該考慮擁有一個謂詞「迴文/ 1」,只有當它的論點是迴文時,它才能成功。然後有一個單獨的謂詞遍歷你的列表,並使用'palindrome/1'來檢查每個謂詞,如果成功,則將它包含在新列表中,或者使用'findall/3',條件是'(member(W,WordLilst ),迴文(W))'。 – lurker