写入 gprolog 中的文件
如何将从 prolog 程序获得的所有解决方案写入文件?
How do I write all the solutions obtained from a prolog program to a file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何将从 prolog 程序获得的所有解决方案写入文件?
How do I write all the solutions obtained from a prolog program to a file?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
简短的答案是将调用“解决方案”谓词嵌套在重复/失败循环中,在将解决方案写入文件的倒数第二个步骤中。
由于该帖子涉及哪种解决方案的详细信息(因此,术语的写作可能有多么困难,例如,如果希望能够通过在某个时候重新读取书面文件来重新恢复一个或多个条款) ,让我们从一个简单的插图开始,其中解决方案只是整数。
我们有以下非确定性谓词:
note for/3 是GNU Prolog的内置谓词。 Swi-Prog在/3 和Amzi之间具有相似的谓词! Prolog具有/4 的,有一个额外的论点,使得增加是+1以外的东西。用户实现将是:
使得目标
mySolution(x)
将以有限数量的方式成功。可以通过使用GNU-Prog的流师或进行控制台输出的命令行重定向来实现文件输出。我们将说明第一种可能性,尽管在许多情况下,第二种可能更简单,更灵活。
像许多Prolog实施一样,GNU-Prolog在 Write 谓词上提供了几种流和非流式变体,您可以找到在此相关文档。对于打开和 close 看此链接和该链接。
添加:我在 nl/1 呼叫中投掷以分离输出文件中的解决方案。
The short answer is to nest the call to your "solutions" predicate inside a repeat/fail loop, at the penultimate step of which the solution is written to a file.
Since the post is short on details of what kind of solution is involved (and thus how difficult the writing of terms might be, e.g. if it is desired to be able to reinstantiate one or more terms from reading the written file back at some point), let's start with a simple illustration, where solutions are just integers.
We have the following nondeterministic predicate:
Note for/3 is a built-in predicate for GNU Prolog. SWI-Prolog has the similar predicate between/3, and Amzi! Prolog has for/4 with an extra argument allowing the increment to be something other than +1. A user implementation would be:
such that the goal
mySolution(X)
will succeed in a predictably finite number of ways.The file output could be achieved either by using GNU-Prolog's stream faculties, or by doing a command-line redirection of console output. We'll illustrate the first possibility although the second one may be simpler and more flexible in many cases.
Like many Prolog implementations, GNU-Prolog offers several stream and non-stream variants on the write predicate, and you can find here the relevant documentation. For open and close look at this link and that link.
Added: I threw in a nl/1 call to separate the solutions in the output file.