我刚开始学习Prolog,对递归概念感到困惑。现在,仅出于练习的目的,我正在尝试编写一个程序,将10个数字附加到列表中,然后打印出该列表。
这个程序的自我规定是,列表必须在主述语中“声明”(我不确定这是否是Prolog中的正确单词),并调用另一个谓词来将数字附加到列表中。
这是我目前所拥有的,但我知道它行不通,因为我试图在addToList谓词的末尾重新定义List,而这在该语言中是不允许的。
这个程序需要通过以下方式启动:
这个程序的自我规定是,列表必须在主述语中“声明”(我不确定这是否是Prolog中的正确单词),并调用另一个谓词来将数字附加到列表中。
这是我目前所拥有的,但我知道它行不通,因为我试图在addToList谓词的末尾重新定义List,而这在该语言中是不允许的。
% Entry point that declares a list (`List`) to store the 10 numbers
printList(List) :-
addToList(0, List),
writeln(List).
% Base case - once we hit 11 we can stop adding numbers to the list
addToList(11, _).
% First case - this predicate makes adding the first number easier for me...
addToList(0, List) :-
append([], [0], NewList),
addToList(1, NewList),
append([], NewList, List). % This is valid, but List will just be [0] I think..
% Cases 1-10
addToList(Value, List) :-
append(List, [Value], NewList),
NextVal is Value+1,
addToList(NextVal, NewList),
append([], NewList, List). % This is INVALID since List is already defined
这个程序需要通过以下方式启动:
printList(List).
有没有简单的方法更改我编写的错误程序,使其能够正确运行?我非常困惑如何获取存储在List
中的数字。