【问题标题】:SWI Prolog - Recursion with listsSWI Prolog - 列表递归
【发布时间】:2017-12-08 19:27:08
【问题描述】:

我是 ProLog 的新手,我在理解列表上的递归时遇到了一些麻烦。

我坚持这个练习。基本上给出了我需要将意大利数字列表转换为英文数字的词汇。

这是我的知识库。

tran(uno, one).
tran(due, two).
tran(tre, three).
tran(quattro, four).
tran(cinque, five).
tran(sei, six).
tran(sette, seven).
tran(otto, eight).
tran(nove, nine).

listran(L,[]).
listran(L,[H|T]) :- tran(H,E), listran([E|L],T).

这个程序应该给出翻译后的列表(以相反的顺序)。但是,它只在我通过时输出 true

?- listran(X, [uno, due, tre]).

我试图追踪它,似乎最后删除了??我翻译列表中的所有元素。这是跟踪输出。

[trace]  ?- listran(X,[uno,due,tre]).
   Call: (8) listran(_5566, [uno, due, tre]) ? creep
   Call: (9) tran(uno, _5820) ? creep
   Exit: (9) tran(uno, one) ? creep
   Call: (9) listran([one|_5566], [due, tre]) ? creep
   Call: (10) tran(due, _5826) ? creep
   Exit: (10) tran(due, two) ? creep
   Call: (10) listran([two, one|_5566], [tre]) ? creep
   Call: (11) tran(tre, _5832) ? creep
   Exit: (11) tran(tre, three) ? creep
   Call: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (11) listran([three, two, one|_5566], []) ? creep
   Exit: (10) listran([two, one|_5566], [tre]) ? creep
   Exit: (9) listran([one|_5566], [due, tre]) ? creep
   Exit: (8) listran(_5566, [uno, due, tre]) ? creep
true.

谁能帮我理解这个小问题?

提前谢谢你。

【问题讨论】:

    标签: recursion prolog


    【解决方案1】:

    问题出在两个子句中:

    listran(L,[]).
    listran(L,[H|T]) :- tran(H,E), listran([E|L],T).
    

    在这里您声明:翻译 H 并将其放置到 L 的头部并继续,这适用于每个 L,您需要明确声明 L 的当前头部是 E 而不是添加 E:

    listran([],[]).
    listran([E|T1],[H|T]) :- tran(H,E), listran(T1,T).
    

    这里你说第一个列表的头部是 E 并继续休息,直到两个列表都为空的基本情况。

    【讨论】:

      【解决方案2】:

      一个有趣(和“序言”)的方法是使用 DCG:

      tran(uno) --> [one].
      tran(due) --> [two].
      tran(tre) --> [three].
      tran(quattro) --> [four].
      tran(cinque) --> [five].
      tran(sei) -->  [six].
      tran(sette) -->  [seven].
      tran(otto) -->  [eight].
      tran(nove) --> [nine].
      
      listran(In,Out) :-
          phrase(trans(In), Out).
      
      trans([]) --> [].
      
      trans([H|T]) --> tran(H), trans(T).
      

      【讨论】:

        猜你喜欢
        • 2014-05-09
        • 2012-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多