写入 gprolog 中的文件

发布于 2024-11-03 12:19:25 字数 35 浏览 4 评论 0原文

如何将从 prolog 程序获得的所有解决方案写入文件?

How do I write all the solutions obtained from a prolog program to a file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情话已封尘 2024-11-10 12:19:25

简短的答案是将调用“解决方案”谓词嵌套在重复/失败循环中,在将解决方案写入文件的倒数第二个步骤中。

由于该帖子涉及哪种解决方案的详细信息(因此,术语的写作可能有多么困难,例如,如果希望能够通过在某个时候重新读取书面文件来重新恢复一个或多个条款) ,让我们从一个简单的插图开始,其中解决方案只是整数。

我们有以下非确定性谓词:

mySolution(X) :- for(X,1,10).

note for/3 是GNU Prolog的内置谓词。 Swi-Prog在/3 和Amzi之间具有相似的谓词! Prolog具有/4 ,有一个额外的论点,使得增加是+1以外的东西。用户实现将是:

for(Low,Low,High) :- Low =< High.
for(New,Low,High) :-
    Now is Low + 1,
    Now =< High,
    for(New,Now,High).

使得目标mySolution(x)将以有限数量的方式成功。

可以通过使用GNU-Prog的流师或进行控制台输出的命令行重定向来实现文件输出。我们将说明第一种可能性,尽管在许多情况下,第二种可能更简单,更灵活。

main :-
    open('myOutput.txt',write,ID),
    (   ( mySolution(X), write(ID,X), nl(ID), fail )
      ; close(ID)
    ).

像许多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:

mySolution(X) :- for(X,1,10).

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:

for(Low,Low,High) :- Low =< High.
for(New,Low,High) :-
    Now is Low + 1,
    Now =< High,
    for(New,Now,High).

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.

main :-
    open('myOutput.txt',write,ID),
    (   ( mySolution(X), write(ID,X), nl(ID), fail )
      ; close(ID)
    ).

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文