Read a file line by line in Prolog

You can use read to read the stream. Remember to invoke at_end_of_stream to ensure no syntax errors. Example: readFile.pl main :- open(‘myFile.txt’, read, Str), read_file(Str,Lines), close(Str), write(Lines), nl. read_file(Stream,[]) :- at_end_of_stream(Stream). read_file(Stream,[X|L]) :- \+ at_end_of_stream(Stream), read(Stream,X), read_file(Stream,L). myFile.txt ‘line 0’. ‘line 1’. ‘line 2’. ‘line 3’. ‘line 4’. ‘line 5’. ‘line 6’. ‘line 7’. ‘line … Read more

Stack overflow in Prolog DCG grammar rule: how to handle large lists efficiently or lazily

As a general remark you will find more on SO about it under the name library(pio). Also the way to use it cleanly is rather: :- use_module(library(pio)). Your example is way too complex, so I will only consider a slightly simpler case, a newline separated list of numbers: nats([]) –> []. nats([N|Ns]) –> nat(N), newline, … Read more