简体   繁体   中英

Prolog - How to write all prolog answers to .txt file?

man(alan).
man(john).
man(george).

list_all:-
  man(X),
  write(X),
  fail.

Question ?-list_all gives the answer:

alan
john
george
false

So I have all the men from the database. It works! My problem: I want to get the same list, but exported to .txt file. I tried to use this code to do this:

program  :-
  open('file.txt',write,X),
  current_output(CO),
  set_output(X),
  man(X),
  write(X),
  fail,
  close(X),
  set_output(CO).

The effect is: Program gives answer false and text: alan john george are not in .txt file - because of using fail predicate.

Is there an option to get all the items in the list into a .txt file (writing all options which are in database) without using fail predicate?

How can I do this? Please help me.

You're almost there. But the call to fail/0 prevents the stream to be closed. Try for example:

program :-
    open('file.txt',write, Stream),
    (   man(Man), write(Stream, Man), fail
    ;   true
    ),
    close(Stream).

An alternative using the de facto standard forall/2 predicate could be:

program :-
    open('file.txt',write, Stream),
    forall(man(Man), write(Stream,Man)),
    close(Stream).

, , ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM