2

我正在尝试编写一个递归函数,将列表向下传递给自身,并在每个级别向该列表添加一个元素。最终列表应作为谓词的解决方案报告回来。但我无法弄清楚如何做到这一点。问题的形式基本上是这样的:

solve(List, NumberOfSteps) :- NumberOfSteps = 10 . //Stops after 10 recursive steps
solve(List, NumberOfSteps) :-
    append NumberOfSteps to List,
    NumberOfStepsIncremented is NumberOfSteps + 1,
    solve(List, NumberOfStepsIncremented) .

所以我在这里我想调用solve(List, 1) 并让Prolog 返回一个看起来像这样的答案:

List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ;
true

我可以让 Prolog 创建列表并在最后打印出来。我可以通过使用内置的预测 append(List, NumberOfSteps, List2) 然后通过递归传递 List2 并在最后打印它来做到这一点,但是 List 和 List2 在那里并没有统一,Prolog 给出的实际答案我是列表 = [] ; 真的

我有一种感觉,我可能以错误的方式处理问题,但我被卡住了!

谢谢。

4

2 回答 2

1

I figured it out. This is what it should have looked like:

solve(List, NumberOfSteps) :- NumberOfSteps = 10 . //Stops after 10 recursive steps
solve([LHead | LTail], NumberOfSteps) :-
    LHead = NumberOfSteps,
    NumberOfStepsIncremented is NumberOfSteps + 1,
    solve(LTail, NumberOfStepsIncremented) .
于 2012-10-14T18:06:48.807 回答
1

I'll extend the comment by Will Ness to your answer and will show the simpler correction:

solve([NumberOfSteps], NumberOfSteps) :-
    NumberOfSteps = 10, !. % Stops after 10 recursive steps
solve([LHead | LTail], NumberOfSteps) :-
    LHead = NumberOfSteps,
    NumberOfStepsIncremented is NumberOfSteps + 1,
    solve(LTail, NumberOfStepsIncremented) .
于 2012-10-15T12:11:30.453 回答