【发布时间】:2015-11-05 21:25:30
【问题描述】:
我必须编写一个函数,从给定列表中过滤掉回文(回文是反向相同的单词,如 abba)
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).
毕竟我误解了 Prolog 中的递归。谢谢@repeat 和@lurker
【问题讨论】:
-
@lurker 我有一个字符串列表,这个程序检查它的元素 (["abba","pizza","tomato"] = ["abba"]) 是否是回文并且只返回结果是回文
-
好的,很抱歉我误会了。您可能应该考虑有一个谓词
palindrome/1,只有当它的论点是回文时才会成功。然后有一个单独的谓词遍历您的列表并使用palindrome/1检查每个谓词,如果成功则将其包含在新列表中,或者使用findall/3,条件为(member(W, WordLilst), palindrome(W))。
标签: list recursion prolog reverse