Read lines of STDIN until EOF into a list

I’m using: SWI-Prolog version 9.0.4 for x86_64-linux

I want the code to: read lines of STDIN until EOF into a single list.

But what I’m getting is:

$ echo -e "hi\nthere" | swipl
Welcome to SWI-Prolog (threaded, 64 bits, version 9.0.4)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit
For built-in help, use ?- help(Topic). or ?- apropos(Word).

ERROR: Stream user_input:8:5 Syntax error: Unexpected end of file

% halt

I attempted using bagof/3 to collect all the possible values of S into a list but that didn’t work as well.

My code looks like this:

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

Did you see the example code under the docs for read_string/5? It says “backtrack over lines in a file”. If you took that you could maybe use it with bagof/3, like this:

$ cat
main :-
    bagof(Line, stream_line(user_input, Line), Lines),
    format('~w~n', [Lines]).

stream_line(In, Line) :-
    (   read_line_to_string(In, Line0),
        Line0 \== end_of_file
    ->  Line0 = Line
    ;   !,
$ echo -e "hi\nthere" | swipl -g main -t halt

But this is not how you’d really do it, probably, there is another example under read_string/3, “read all lines to a list”. It would look like this:

$ cat
main :-
    stream_lines(user_input, Lines),
    format('~w~n', [Lines]).

stream_lines(In, Lines) :-
    read_string(In, _, Str),
    split_string(Str, "\n", "\n", Lines).
$ echo -e "hi\nthere" | swipl -g main -t halt

Please note that there are many small things that could be done differently. This was now just the lowest effort, meaning I just copy-pasted the example code and ran it.

1 Like