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

I am trying to write a predicate to accept a string from an input file. Each time it is used, it should give the next line until it reaches the end of the file, after which it should return false. Something like that:

database :-
    see('blah.txt'),
    loop,
    seen.

loop :-
    accept_line(Line),
    write('I found a line.\n'),
    loop.

accept_line([Char | Rest]) :-
    get0(Char),
    C =\= "\n", 
    !,
    accept_line(Rest).
accept_line([]).

Obviously this does not work. It works for the first line of the input file, and then the loop endlessly. I see that I need to have some line, for example "C = \ = -1", somewhere to check the end of the file, but I don’t see where it will go.

So an example of input and output might be ...

INPUT
this is
an example

OUTPUT
I found a line.
I found a line.

Or am I doing this completely wrong? Maybe there is a built-in rule that makes this simple?

+4
source share
2 answers

SWI-Prolog - DCG , "", library(pio) DCG .

, DCG phrase/2 .

DCG, , .

:

:- use_module(library(pio)).

:- set_prolog_flag(double_quotes, codes).

lines --> call(eos), !.
lines --> line, { writeln('I found a line.') }, lines.

line --> ( "\n" ; call(eos) ), !.
line --> [_], line.

eos([], []).

:

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

, DCG :

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

.

+5

, . library (readutil), read_line_to_codes/2, , .

, / , , , ISO. "/ " ", , SWI-Prolog. :

get_line(L) :-
    get_code(C),
    get_line_1(C, L).

get_line_1(-1, []) :- !. % EOF
get_line_1(0'\n, []) :- !. % EOL
get_line_1(C, [C|Cs]) :-
    get_code(C1),
    get_line_1(C1, Cs).

, , ; read_line_to_codes/2 (readutil).

strings Prolog, . , , :

read_string(user_input, _, S),
split_string(S, "\n", "", Lines)

. read_string/5 linewise.

PS. see seen .. :

setup_call_cleanup(open(Filename, read, In),
        read_string(In, N, S), % or whatever reading you need to do
        close(In))
+3

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


All Articles