【问题标题】:Prolog recursion not working as intendedProlog 递归未按预期工作
【发布时间】: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


【解决方案1】:

使用广泛使用的列表谓词reverse/2 像这样定义palindrome/1 怎么样?

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

【讨论】:

  • 这可能行得通,但是您有什么提示可以告诉我为什么我不能像我想要的那样返回列表 Z。我真的很想知道我做错了什么? (除了实现,也许我在序言中的递归通常做错了)@repeat
  • @DarkFeud 看到我的 cmets 到你原来的帖子。您应该使用在此处显示的重复谓词 palindrome/1 尝试递归 palindromes(List, Palindromes) 谓词。
  • @lurker。似乎我解决了错误的问题,不是OP提出的问题,而是正确的问题:)
猜你喜欢
  • 2015-01-17
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多