开发者

Writing to a file in gprolog

开发者 https://www.devze.com 2023-02-28 22:49 出处:网络
How do I write all the so开发者_运维问答lutions obtained from a prolog program to a file?The short answer is to nest the call to your \"solutions\" predicate inside a repeat/fail loop, at the penultim

How do I write all the so开发者_运维问答lutions obtained from a prolog program to a file?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号