SWI-Prolog predicate for reading in lines from input file -


i'm trying write predicate accept line input file. every time it's used, should give next line, until reaches end of file, @ point should return false. this:

database :-     see('blah.txt'),     loop,     seen.  loop :-     accept_line(line),     write('i found line.\n'),     loop.  accept_line([char | rest]) :-     get0(char),     c =\= "\n",      !,     accept_line(rest). accept_line([]). 

obviously doesn't work. works first line of input file , loops endlessly. can see need have line "c =\= -1" in there somewhere check end of file, can't see it'd go.

so example input , output be...

input example  output found line. found line. 

or doing wrong? maybe there's built in rule simply?

in swi-prolog, elegant way first use dcg describe "line" means, , use library(pio) apply dcg file.

an important advantage of can apply the same dcg on queries on toplevel phrase/2 , not need create file test predicate.

there dcg tutorial explains approach, , can adapt use case.

for example:

:- use_module(library(pio)).  :- set_prolog_flag(double_quotes, codes).  lines --> call(eos), !. lines --> line, { writeln('i found line.') }, lines.  line --> ( "\n" ; call(eos) ), !. line --> [_], line.  eos([], []). 

example usage:

?- phrase_from_file(lines, 'blah.txt'). found line. found line. true. 

example usage, using same dcg parse directly character codes without using file:

?- phrase(lines, "test1\ntest2"). found line. found line. true. 

this approach can extended parse more complex file contents well.


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -