如何在 Prolog 中编写一个程序,使用递归打印从 1 到 10 的数字?
如何在 Prolog 中编写一个程序,使用递归打印从 1 到 10 的数字?
我尝试了以下方法,但不起作用,你能告诉我为什么吗?
print_numbers(10) :- write(10).
print_numbers(X) :- write(X),nl,X is X + 1, print_numbers(X).
How would you code a program in Prolog to print numbers from 1 to 10 using recursion?
I've tried the following but it doesn't work, can you tell me why?
print_numbers(10) :- write(10).
print_numbers(X) :- write(X),nl,X is X + 1, print_numbers(X).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的代码非常接近工作。问题是你不能重用X,一旦实例化,就不能更改(参见此处了解更多详情)。使用新变量,如下所示:
将剪切 (!) 添加到末尾将阻止解释器询问您是否想查看更多结果。
Your code is very close to working. The problem is that you cannot reuse X, once it is instantiated, it cannot be changed (see here for more details). Use a new variable, like this:
Adding the cut (!) to the end will prevent the interpreter from asking if you want to see more results.
自从我写任何序言以来已经认真很长一段时间了,但我可能会做一些不同的事情。类似这样的东西,虽然我现在无法测试。
这里的一个关键区别是
!
或剪切操作,它会停止回溯。如果不包含它,那么当 X 为 10 时,您将得到第一个子句的解决方案,但如果您要求第二个解决方案,它也会回溯并匹配第二个子句。这会导致数字列表比您想要的大得多。Been a seriously long time since I wrote any prolog but I'd probably do things just a little differently. Something like this, though I can't test it at the momment.
A key difference here is the
!
, or cut operation, which stops backtracking. If you don't include it then you will get a solution with the first clause whenX
is 10,but if you ask for a second solution it will backtrack and match the second clause as well. That would result in a much larger list of numbers than you want.只需从终端调用defineXandY
Just call defineXandY from terminal