Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

prolog

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.

like image 400
Przemek Avatar asked Feb 15 '23 08:02

Przemek


1 Answers

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).

, , ,

like image 75
Paulo Moura Avatar answered Feb 17 '23 21:02

Paulo Moura