Write to file (Prolog)

I am trying to iterate over a list and write it to a file, why does the following not work?

loop_through_list(List) :- member(Element, List), write(Element), write(' '), fail. write_list_to_file(Filename,List) :- tell(Filename), % open file to be written loop_through_list(List), told. % flush buffer 
+6
source share
3 answers

First, why this fails:
You use to not provoke backtracking, which may be a good technique, but does not exist. Because it will make your predicate false at the end when the member has run out of decisions. Then, as soon as the loop_through_list is false, it is said that it has not been reached and the recording has not been performed properly (when I test it, the file is created, but nothing is written).
If you use:

 loop_through_list([]). loop_through_list([Head|Tail]) :- write(Head), write(' '), loop_through_list(Tail). 

instead it works.

But even if this code works, you can use open (file name, record, stream), write (stream, element) and close (stream), and do not tell and explain the reasons explained in the link at the bottom of this answer. For instance:

 loop_through_list(_File, []) :- !. loop_through_list(File, [Head|Tail]) :- write(File, Head), write(File, ' '), loop_through_list(File, Tail). write_list_to_file(Filename,List) :- open(Filename, write, File), loop_through_list(File, List), close(File). 

or

 loop_through_list(File, List) :- member(Element, List), write(File, Element), write(File, ' '), fail. write_list_to_file(Filename,List) :- open(Filename, write, File), \+ loop_through_list(File, List), close(File). 

using your code and the joel76 trick.

See Prolog to save a file in an existing file.
It covers the same issue.

+7
source

I see no reason to use this method to write a list to a file.
Prolog programming should not include loops at all; moreover, it is not a loop structure, it is more like a hack (or even abuse).
(and just like your case leads to unexpected errors and problems)

Just use recursion and print the list items:

 write_list([]). write_list([H|T]):- write(H), write(' '), write_list(T). 

more elegant and can be more efficient.

other than that using open / 4 etc. (ISO IO) instead of tell / 1, etc. (Edinburgh IO) is generally better; check false message

+3
source

the predicate loop_through_list (List) always fails, so for successful operation you just need to write \ + loop_through_list (List),

+2
source

Source: https://habr.com/ru/post/902503/


All Articles