【问题标题】:Prolog not recursing as intendedProlog 未按预期递归
【发布时间】:2015-01-17 17:44:18
【问题描述】:

我有一个接收列表列表的函数,我想将内部列表中的每个 int 模式匹配到特定模式。列表列表中有 9 个列表(称为 A),列表中的每个列表也包含 9 个 int。我想使用递归一次遍历每个列表 3,并适当地打印,但我似乎没有超过我的 main 函数中递归的第一步。 代码清晰:

print_tail([]).
print_tail([A,B,C|Ts]) :-
  write('print_tail called'), nl,
  print_tail_h(A,B,C),
  write('Recursed'),             % this never prints
  print_tail(Ts).                % this never happens

% working, or so it seems 
print_tail_h([A1,A2,A3|As],[B1,B2,B3|Bs],[C1,C2,C3|Cs]) :-
  printer([A1,A2,A3,B1,B2,B3,C1,C2,C3]),nl,
  write('Helper recursed'), nl,
  print_tail_h(As, Bs, Cs).

printer([]).
printer([X|Xs]) :-
  write(X),
  printer(Xs).

我正在调用这个函数来测试它:

test_print_tail :-
  X = [
             [1,2,3,4,5,6,7,8,9],
             [1,2,3,4,5,6,7,8,9],
             [1,2,3,4,5,6,7,8,9],   % stops recursing here
             [1,2,3,4,5,6,7,8,9],
             [1,2,3,4,5,6,7,8,9],
             [1,2,3,4,5,6,7,8,9],
             [1,2,3,4,5,6,7,8,9],
             [1,2,3,4,5,6,7,8,9],
             [1,2,3,4,5,6,7,8,9]],
  print_tail(X).

我的输出如下:

print_tail called
123123123
Helper recursed
456456456
Helper recursed
789789789
Helper recursed
false.

感觉它应该可以工作,但显然我做错了什么。任何帮助将不胜感激。

【问题讨论】:

    标签: recursion prolog


    【解决方案1】:

    print_tail_h 递归调用自身,但没有定义基本情况。一旦 As、Bs 和 Cs 为空,谓词就会失败,进而导致 print_tail 也失败。

    只需添加另一个子句即可解决此问题:

    print_tail_h([],[],[]).
    

    输出:

    print_tail called
    123123123
    Helper recursed
    456456456
    Helper recursed
    789789789
    Helper recursed
    Recursedprint_tail called
    123123123
    Helper recursed
    456456456
    Helper recursed
    789789789
    Helper recursed
    Recursedprint_tail called
    123123123
    Helper recursed
    456456456
    Helper recursed
    789789789
    Helper recursed
    Recursed
    

    【讨论】:

    • 非常感谢!我完全没有看到
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    相关资源
    最近更新 更多